Click here to Skip to main content
14,698,806 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
#include<stdio.h>
#include<math.h>
int main()
{
    int a=2,b;
    b=a++ + a-- + ++a + --a;
    printf("%d %d",a,b);
}




output is 2 9 why?????
Posted
Updated 19-Mar-20 7:43am

Ahh, I expected this one from your last one...

The pre-increment operator and the + operators have equal precedence. That means which one is done first is completely compiler dependent. This is called undefined behavior and these types of statements should be avoided at all costs.

Why does it happen in your compiler? Its simply the precedence that the compiler decided to apply the + and ++/-- prefix operators in. I didn't work through your equation but it can either do the addition first, or the subtraction first.

There has recently been a lively discussion on this here[^], read the thread to see what is said, and ignore the guy who doesn't get it :)
   
The first result (2) is pretty obvious, because a is incremented two times and decremented two times. Hence a has afterwards the same value as before.

The second result (9) is the one that is not so easy to see. The value of b depends on the time when the compiler chooses to do the post-increment and post-decrement operations. Your compiler has chosen to them after the entire expression has been completed. Hence b is computed as:
b = 2 + 2 + 3 + 2;
    // afterwards the post-increment and post-decrement operators
    // are performed

Note that with pre-increment and pre-decrement operations the compiler has no other choice than doing them right away. Hence the last two values are 3 and 2.

As Ron has correctly pointed out in solution 1, the result of this expression is actually undefined. The compiler could have chosen to perform the post-increment and post-decrement operations at an earlier time and that could have resulted in:
b = 2 + 3 + 3 + 2; // == 10

It certainly is no good idea to write statements like this. The case here is a little constructed just to demonstrate what can happen if you abuse the post-increment/decrement operators.
   
int a=2,b;
b=a++ + a-- + ++a + --a;
b=2+3+3+2

Ans is (2,10)
   
Comments
Richard Deeming 19-Mar-20 12:50pm
   
Read the previous solutions. The behaviour is undefined, and the two solutions posted six years ago already explain why.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900