C++ lvalue references cannot bind to rvalues: detect the error with post-increment operands.
#include
int main() {
int m = 2, n = 6;
int &x = m++;
int &y = n++;
m = x++;
x = m++;
n = y++;
y = n++;
cout << m << " " << n;
return 0;
}
-
AThe program will print output 3 7.
-
BThe program will print output 4 8.
-
CThe program will print output 5 9.
-
DThe program will print output 6 10.
-
EIt will result in a compile time error.
Answer
Correct Answer: It will result in a compile time error.
Explanation
Introduction / Context: This question targets reference binding rules in C++. Non-const lvalue references (int&) cannot bind to temporaries (rvalues). Using a post-increment expression as a reference initializer creates such a temporary, triggering a compilation error.
Given Data / Assumptions:
- int &x = m++; and int &y = n++;
- Post-increment yields rvalues (the old values), not lvalues.
- Classic iostream.h headers do not affect this rule.
Concept / Approach: The initializer for x is m++ which is an rvalue; a non-const lvalue reference cannot bind to it. The same applies to y. Modern C++ permits binding a const reference to a temporary, but not a non-const reference. Therefore compilation fails before any runtime output is possible.
Step-by-Step Solution:
Recognize m++ / n++ are rvalues.int& requires an lvalue; binding fails.Compilation stops at the first invalid binding.Verification / Alternative check: Replacing with const int &x = m++; and const int &y = n++; would compile (binding to temporaries allowed for const refs), though subsequent ++ uses would fail due to constness.
Why Other Options Are Wrong:
- All numeric outputs assume successful compilation and execution.
Common Pitfalls: Assuming references can bind to any expression; confusing lvalues and rvalues; forgetting the special rule for const references to temporaries.
Final Answer: It will result in a compile time error.