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);

20th Nov 2020, 12:31 PM
Tom Tanner
Tom Tanner - avatar
5 Answers
+ 1
There's a sequence point in the expression which leads to an undefined behaviour .
20th Nov 2020, 12:59 PM
Hima
Hima - avatar
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
20th Nov 2020, 12:56 PM
NavyaSri
NavyaSri - avatar
0
Tom Tanner Nope b value is 5
20th Nov 2020, 1:05 PM
NavyaSri
NavyaSri - avatar
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.
23rd Nov 2020, 9:14 AM
LastSecond959
LastSecond959 - avatar
- 1
Then b-- will make b's value 4 not 5
20th Nov 2020, 1:01 PM
Tom Tanner
Tom Tanner - avatar