-3

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
Stephan
  • 531
  • 3
  • 16
  • 1
    Which version of C++ are you compiling for? – chris Feb 24 '19 at 19:32
  • 1
    IIRC the evaluation order of stuff into a stream is not guaranteed. i.e. `a++` can be evaluated AFTER `++a`. The only guarantee is the results being shown in certain order. https://stackoverflow.com/questions/14809978/order-of-execution-in-operator – Rietty Feb 24 '19 at 19:34
  • You should take a look at [Order of evaluation](https://en.cppreference.com/w/cpp/language/eval_order) – t.niese Feb 24 '19 at 19:38
  • @chris C++ 11. I got order is undefined. Thanks – Ashish kumar Feb 26 '19 at 02:32

1 Answers1

1

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.

Rietty
  • 1,116
  • 9
  • 24
t.niese
  • 39,256
  • 9
  • 74
  • 101