C++ with enum and references: is this code valid, and if so what is printed?\n\n#include<iostream.h>\nenum xyz { a, b, c };\nint main()\n{\n int x = a, y = b, z = c;\n int &p = x, &q = y, &r = z;\n p = ++x;\n q = ++y;\n r = ++c; // attempt to increment an enum constant\n cout << p << q << r;\n return 0;\n}

Difficulty: Easy

Correct Answer: It will result in a compile time error.

Explanation:


Introduction / Context:
This question checks whether enum constants are modifiable lvalues. In C++, named enumeration constants are not variables; they are constant integral values and cannot be incremented.


Given Data / Assumptions:

  • enum xyz { a, b, c }; defines constants a=0, b=1, c=2.
  • Later code attempts r = ++c;.


Concept / Approach:
An expression like ++c requires c to be a modifiable lvalue. Enum enumerators are not variables; they are constant values in the type's value space. Therefore the increment is ill-formed, causing a compile-time error.


Step-by-Step Solution:
1) p = ++x; and q = ++y; are fine because x and y are variables. 2) ++c attempts to modify an enumerator, which is not allowed. 3) The program fails to compile at that line.


Verification / Alternative check:
Replace r = ++c; with r = ++z; (where z is an int) to obtain a compilable variant that prints values.


Why Other Options Are Wrong:
All printed outputs assume compilation success, which is false here.


Common Pitfalls:
Confusing enumerator names with variables; assuming they can be incremented like normal integers.


Final Answer:
Compile-time error due to attempting to increment an enum constant.

More Questions from References

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion