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; }
4 Antworten
+ 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
+ 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
+ 1
nAutAxH AhmAd tq bro
0
C++ Soldier (Babak) sure