C++ Programming - References - Discussion

Discussion Forum : References - Programs (Q.No. 4)
4.
Which of the following statement is correct about the program given below?
#include<iostream.h> 
int main()
{
    int x = 10;
    int &y = x;
    x = 25;
    y = 50;
    cout<< x << " " << --y;
    return 0; 
}
The program will print the output 50 49.
It will result in a compile time error.
The program will print the output 50 50.
The program will print the output 49 49.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
13 comments Page 1 of 2.

Aakash said:   1 decade ago
Change in y will also b reflected in x. thats why x=y=50;

Then a decrement in y therefore in x too.

And answer is 49 49.

Sada said:   1 decade ago
How reflected?

Aayush said:   1 decade ago
Because there is & so it will act as an alias.

&y=x means that every change in x will be the same in y.

x and y will be the same :).

Vikas said:   10 years ago
Because here value of x is assigned in y. So every change in y also affect value of x.

Asaad said:   10 years ago
I can also add that x takes the value of y and also y takes the value of x. This appears when you put y=50;

And then x=25;

The output will become 24 24.

Just try it.

Bhawna said:   10 years ago
If we create an integer variable and then create a reference which refers to this, any mention of the reference will be exactly the same as a mention to original variable.

Muhammad Mazhar said:   9 years ago
There is a confusion that the value of x is printed first, then -- decrement the value of y and print.

According to this, the value should be 50 49.

Meenakshi L said:   9 years ago
Is y = x same as &y=x?
As you said before the value of x is stored in y. So, we can use y=x is enough.
Why we need to use &y=x?

Kjell said:   8 years ago
What compiler are you using?

I verified it with Apple LLVM 8.0 and g++ 5.4.0:

1. the result is 50 49,
2. #include <iostream.h> is not valid since a long time, it must be #include <iostream>
<< Is evaluated left to right, the decrement will happen after x was already streamed.

Abhishek said:   5 years ago
Yes, I agree, The answer will be 50 49.


Post your comments here:

Your comments will be displayed after verification.