-4

According to the concept of pre-increment and post-increment operator the output of the following code should be (8+8) = 16, but in the compiler it is evaluated to 17. Please explain with steps.

#include <iostream>

using namespace std;

int main()
{
    int n = 7;
    int x = ++n + n++;
    cout << x;

    return 0;
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64

1 Answers1

4

following code should be (8+8) = 16

That's not correct.


Please explain with steps.

This expression:

++n

Modifies n.

This expression:

n++

Modifies n.

This expression:

++n + n++

Has two modifications on the same variable that are unsequenced in relation to each other. Hence, the behaviour of the program is undefined.

Since the bahviour is undefined, there is no output that "should" or "shouldn't" be.

eerorika
  • 232,697
  • 12
  • 197
  • 326