Question:medium

What is the output of the following code snippet? verbatim #include <iostream> using namespace std; int main() int x = 5; int y = x++; cout << y; return 0; verbatim

Show Hint

Remember the difference between pre-increment (`++x`) and post-increment (`x++`). Pre-increment: increment first, then use the value. Post-increment: use the value first, then increment.
Updated On: Jul 2, 2026
  • 5
  • 6
  • 0
  • Compilation error
Show Solution

The Correct Option is A

Solution and Explanation

Step 1: Recall exactly what post-increment does.
The expression x++ is different from ++x. With post-increment, the current value of x is first used in whatever expression it appears in, and only after that is x actually incremented by one behind the scenes.
Step 2: Trace the two lines of code.
The line int x = 5; sets x to 5. Then int y = x++; takes the current value of x, which is 5, and assigns that value to y first. Only after this assignment does x get bumped up to 6. So after this line, y holds 5 while x holds 6.
Step 3: Confirm what gets printed.
The next line prints the value of y, and since y was fixed at 5 during the assignment step, no matter what happens to x afterward, the value printed is simply 5.
Step 4: Conclude.
The program outputs
\[ \boxed{5} \]
Was this answer helpful?
0