0
Why the output is a=3 b=5 and not a=3 b=4 for the code:
#include <stdio.h> int main(){ int a=2, b=3; b=a++ + b--; printf("a=%d\tb=%d,a,b);
5 ответов
+ 1
There's a sequence point in the expression which leads to an undefined behaviour .
0
Initially a=2 and b=3
And when b=a++ + b-- //these are post increment and post decrement operations
then value becomes b=2 + 3 //first value will assigned then increment(or)decrement will perform. So,
b=5, a=3
0
Tom Tanner Nope b value is 5
0
It's one of the classic undefined behavior, but if you understand how STACK works, you know what's when. When you do b = a++ + b--;, a won't be 3 until it meets a again (as in printf), the same goes for b, b won't be 2 unless it meets b again, so the value used is b = 2 + 3;, BUT b-- will do nothing since you are currently doing an assignment to b, therefore the old b (b--) is not visually seen anymore. So b = 5, a still incremented because there is no "replacement" for a, and it meets a again in printf, so it becomes 3.
If you want b to be 4, try b = a++ + --b;
Remember, this is undefined behavior, and different compilers will react differently.
- 1
Then b-- will make b's value 4 not 5