In C++ (reference declaration syntax), spot the error and determine the outcome. What happens when compiling the following code? #include<iostream.h> int main() { int x = 80; int y& = x; // attempt to declare a reference x++; cout << x << " " << --y; return 0; }

Difficulty: Easy

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

Explanation:


Introduction / Context:
C++ reference declarations must place the ampersand on the declarator, not after the identifier name. The correct form is int &y = x; not int y& = x;.


Given Data / Assumptions:

  • The line int y& = x; is ill-formed.


Concept / Approach:
The compiler parses int y& as an attempt to suffix a symbol with an ampersand, which is not valid C++ syntax. References are part of the type specifier and must precede the variable name (as in pointers).


Step-by-Step Solution:

Compilation fails with a syntax error at '&'.


Verification / Alternative check:
Fixing to int &y = x; then executing would yield "81 81" because y aliases x (after x++ both are 81, and --y prints 80 then decrements, but note the exact sequence). However, as given, it does not compile.


Why Other Options Are Wrong:
They assume successful compilation and execution.


Common Pitfalls:
Misplacing & or * when declaring references or pointers.


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

More Questions from References

Discussion & Comments

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