MCQ
Q.
What will be the output of the following C++ code snippet?
#include
int main() {
int x = 5;
int y = 3;
int result = (x++ * --y) + x;
std::cout << result;
return 0;
}
Correct Answer: B
The correct answer is B.
🔑 Key Points
- The expression is
result = (x++ * --y) + x; - Initially,
x = 5andy = 3. - Evaluation of
(x++ * --y):x++(post-increment): Uses the current value ofx(which is 5) for the operation, and then incrementsxto 6.--y(pre-decrement): Decrementsyto 2, and then uses this new value for the operation.- So,
5 * 2 = 10. After this part,xis 6 andyis 2.
- Evaluation of
+ x: Thexon the right side of the+operator uses its currently updated value, which is 6. - Therefore,
result = 10 + 6 = 16.
📄 Additional Information
- Understanding operator precedence and side effects of increment/decrement operators (
++,--) is crucial. - Pre-increment/decrement (
++x,--x) modifies the variable before its value is used in the expression. - Post-increment/decrement (
x++,x--) uses the variable's original value in the expression, then modifies the variable. - In expressions involving multiple occurrences of the same variable being modified by increment/decrement operators, the order of evaluation within an expression can sometimes lead to undefined behavior if not properly sequenced. However, in this specific case, the parentheses clearly define the order of evaluation for the multiplication, and the final
+ xuses the value ofxafter the previous operations are completed.