What will be the output of the following C++ code?

int x = 5;
int a = x++;
int b = ++x;
cout << a << " " << b << " " << x;
                        

Options

  • A. 5 6 6
  • B. 5 7 7
  • C. 6 7 7
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. 5 7 7

Detailed Explanation

Answer: (B) 5 7 7

x++ is the post-increment operator. It first uses the current value and then increments x.

Initially x = 5, so a = x++ makes a = 5 and then x = 6.

Next, ++x is pre-increment. It increments x first, making it 7, and then assigns that value to b.

Therefore, a = 5, b = 7, and x = 7.