Search code examples
c++operator-precedenceprefix

What is logic behind output of this code postfix and prefix on same varible in one line c++


How for post increment(a++) return 5. As according to operator precedence a++ should execute first and should return 4.

#include <iostream>
using namespace std;
int main()
{
    int a=4,b=4;
    cout<<++b<<" "<<b++<<" "<<a++<<" "<<++a<<endl;
    return 0;
}
Output: 6 4 5 6

Solution

  • You should always compile your code with warnings enabled. The compiler will tell you that the outcome might be undefined:

    prog.cc: In function 'int main()':
    prog.cc:6:22: warning: operation on 'b' may be undefined [-Wsequence-point]
         cout<<++b<<" "<<b++<<" "<<a++<<" "<<++a<<endl;
                         ~^~
    prog.cc:6:41: warning: operation on 'a' may be undefined [-Wsequence-point]
         cout<<++b<<" "<<b++<<" "<<a++<<" "<<++a<<endl;
                                             ^~~
    

    If you want to use and modify one variable with in the same expression, you need to check the order of evaluation and sequence rules to see if it is valid, and what the expected result is.