In C++ (references to arrays), identify the correctness of binding a reference to an array and the subsequent prints. What happens with the following code? #include<iostream.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int &zarr = arr; // attempt to bind an int& to an int[5] for (int i = 0; i <= 4; i++) { arr[i] += arr[i]; } for (i = 0; i <= 4; i++) cout << zarr[i]; return 0; }

Difficulty: Easy

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

Explanation:


Introduction / Context:
This checks your understanding of references to arrays in C++. A reference to a single int cannot be bound to an entire array. The correct type for a reference to this array would be int (&zarr)[5], not int &zarr.


Given Data / Assumptions:

  • arr has type int[5].
  • The code uses int &zarr = arr; which is ill-formed.
  • There is also a scope issue with i in the second loop in older compilers.


Concept / Approach:
Type binding rules require exact matching for references: an int& cannot bind to an int[5]. You must write int (&zarr)[5] = arr; to alias the entire array. Otherwise, the program fails at compile time.


Step-by-Step Solution:

Compilation fails on the line binding zarr. If corrected to int (&zarr)[5], both loops would double each element and print 2 4 6 8 10.


Verification / Alternative check:
Modern compilers clearly report a type mismatch for binding int& to int[5].


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


Common Pitfalls:
Confusing references to the first element (int&) with references to the whole array type (int (&)[N]).


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