0

Folks need explanation for a particular function in c based on prefix operator

int main(){ int x=1; x= ++x + ++x; printf("%d",x); return 0; }

7th Nov 2018, 4:47 AM
Abishek M
Abishek M - avatar
4 odpowiedzi
+ 9
x = 1 x = ++x + ++x --> 1 = ++1 + ++1 When compiler sees first prefix increment operator 2 = 2 + ++2 When compiler sees the second prefix increment operator 3 = 3 + 3 Now compiler will sum both values and assign it to x 3 = 6 --> x = 6
7th Nov 2018, 5:06 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 6
Unfortunately the structure x = ++x + ++x; has undefined behavior in C/C++, " Modifying an object between two sequence points more than once produces undefined behavior. " That means even though the precedence of increment/decrement operator is defined but by combining multiple of them in an expression like that, there's no guarantee what the final result can be. Even something like x = ++x + 1; is still undefined (Wikipedia example). Just take a look the result of the x in two different compilers (clang and g++) https://rextester.com/LJT63493 https://rextester.com/OKAQ48119 _____ https://en.m.wikipedia.org/wiki/Undefined_behavior
7th Nov 2018, 6:51 AM
Babak
Babak - avatar
+ 1
7th Nov 2018, 12:42 PM
Abishek M
Abishek M - avatar
7th Nov 2018, 2:14 PM
Abishek M
Abishek M - avatar