C++ Programming - References - Discussion

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

Tanuja Ankush Gawade said:   1 year ago
#include<iostream.h>
int main()
{
int x = 80;
int y& = x;
x++;
cout << x << " " << --y;
return 0;
}

In the above program "using namespace std; "line or "std" library must be included and The "&" symbol must be placed before the variable name like int &y =x;

Hence there is an error.

Tauseef Sarwar said:   2 years ago
#include<iostream.h>
int main()
{
int x = 80;
int y& = x;
x++;
cout << x << " " << --y;
return 0;
}


@All.
This shows error, but when the ampersand symbol is written before y then the answer will be 81 80.
(1)

Anurag said:   5 years ago
Please note that &y is just creating a reference and reference is automatically deferred so --y is purely a valid operation.

So the answer is 81 80.
(1)

R@j said:   7 years ago
#include <stdio.h>

int main()
{
int x=80;
int &y = x;
x++;
printf("Hello World %d %d ",x, --y);
return 0;
}

And the answer is 80 80.
(2)

Sarvesh karan said:   7 years ago
Why it is compile time error. It should take as bitwise & and then proceed.

Hatos said:   8 years ago
I got this error:

expected initializer before '&' token
int y& = x;
^
Code::Blocks
Release 17.12 rev 11256
g++.exe (GCC) 7.2.0
std = c++1z

Can anyone help me to resolve it?

Vipul said:   8 years ago
cout << x << " " << --y.

This is processed right to left, starting with loading y, decrementing it and so on.

Mohammad Taha said:   9 years ago
int y& is basically a reference variable, and reference variable is internally a constant pointer. And one cannot change constant pointer value. So, it's compile time error.

SAURABH SHARMA said:   9 years ago
It should be y=&x ;
OR
y=y & x;
Here & is BITWISE AND.

#include<iostream.h>
#include<conio.h>r
int main()
{
int x = 80,y=10;
clrscr();
y = y & x;
x++;
cout << x << " " << --y;
getch();
return 0;
}

output.
--------
    64 32 16 8 4 2 1
x = 1 0 1 0 0 0 0
y = 0 0 0 1 0 1 0
--------------------------
y = 0 0 0 0 0 0 0

--y = -1.

Kevin said:   10 years ago
Position of '&' is incorrect.


Post your comments here:

Your comments will be displayed after verification.