C++ Programming - References - Discussion

Discussion Forum : References - Programs (Q.No. 12)
12.
Which of the following statement is correct about the program given below?
#include<iostream.h> 
int main()
{
    int arr[] = {1, 2 ,3, 4, 5}; 
    int &zarr = arr;
    for(int i = 0; i <= 4; i++)
    {
        arr[i] += arr[i];
    }
    for(i = 0; i <= 4; i++)
        cout<< zarr[i]; 
    return 0; 
}
The program will print the output 1 2 3 4 5.
The program will print the output 2 4 6 8 10.
The program will print the output 1 1 1 1 1.
It will result in a compile time error.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
11 comments Page 1 of 2.

Harshad said:   5 years ago
@All.

#include<iostream>
using namespace std;
int main()
{
int arr[] = {1, 2 ,3, 4, 5};
int (&zarr)[5] = arr;
for(int i = 0; i <= 4; i++)
{
arr[i] += arr[i];
}
for(int i = 0; i <= 4; i++)
cout<< zarr[i];
return 0;
}

The above program gives correct Output.
(1)

Waqar Akram said:   5 years ago
@Manish maybe you are right. But if we use int &zarr=arr[5] it will show the next error (i is not initialized).

Ashish said:   5 years ago
Please explain someone correctly.

Manish said:   6 years ago
Here an array of reference is not acceptable, that's why the error occurs.

Kripa Mary Jose said:   6 years ago
This program will not cause any compilation error as;

int & zarr = arr; is not erroneous. Here the base address of the array is passed. I don't understand why its answer is a compilation error then?

Please, anyone explain in clear.

DoanNguyen said:   7 years ago
for(i = 0; i <= 4; i++)
cout<< zarr[i];
return 0;

i no have in scope of for
And &zarr can't cast "int*" to 'int" need cast "&zarr = arr[0] "
- It can't print "zarr[i]" becase it is a pointer we need print " zarr + i".

Chetan said:   7 years ago
Variable i is declared in loop 1.
After the end of the scope, it cannot be accessed.
But in loop 2 it is accessed without declaration will generate the error.
Correct me if I am wrong.
(2)

Suman said:   10 years ago
No here it must be int (&zarr)[5] = arr.

Lavanyeswari motupalli said:   1 decade ago
A reference can be an int, char pointer but not array.

Atul Kumar said:   1 decade ago
Since an array of references is not acceptable.

Hence compile time error occur.


Post your comments here:

Your comments will be displayed after verification.