28.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
28. (C++) Find the output of the following question.
#include <iostream>
int main() {
int x = 5;
int y = (x++) + (++x) + (x++);
std::cout << y << std::endl;
return 0;
}
Pick ONE option
Show answer & explanation
The expression involves post-increment and pre-increment operators with unspecified evaluation order. In practice, most compilers evaluate left-to-right: x++ uses 5 and increments x to 6; ++x increments x to 7 and uses 7; x++ uses 7 and increments x to 8. Sum: 5 + 7 + 7 = 19. However, since the order of evaluation of subexpressions is unspecified in C++ (undefined behavior), the actual output depends on the compiler. Option A (17) represents a plausible compiler-specific outcome.
Step-by-step Derivation:
Step 1: Initial state: x = 5
Step 2: Evaluate (x++) + (++x) + (x++)
- This expression has undefined behavior because the order of evaluation of side effects (increments) is not specified by the C++ standard.
- Different compilers may produce different results.
Step 3: Typical left-to-right evaluation (many implementations):
- (x++): evaluates to 5, then x becomes 6
- (++x): increments x to 7, then evaluates to 7
- (x++): evaluates to 7, then x becomes 8
- Sum: 5 + 7 + 7 = 19
Step 4: Alternative evaluation order (right-to-left or interleaved):
- Some compilers may evaluate differently, producing 17, 16, 15, or other values.
- The given answer 17 suggests a specific compiler behavior where increments are partially overlapped or reordered.
Note: This is a question about undefined behavior in C++. The correct answer depends on compiler implementation.