Explain this program..

Kindly explain the following program how will be executed. Why Y value is assigned -1?

#include<iostream.h>
#include<conio.h>
int &maxref(int &a, int &b)
{
if(a>b)
return a;
else
return b;
}
void main()
{
int x=20, y=30, max=0;
maxref(x,y)=-1;
cout<<"Value of x is:"<,x;
cout<<"Value of y is:"<<y;
getch();

Output:
Value of x is: 20
Value of y is: -1
Perhaps it has to do something with the line
maxref(x,y) = -1;

There is clearly an assignment of -1 to something.

Can you see what is the type of expression maxref(x,y)?
@ r 4 raja
Maybe you can edit your post so that the code is in the "blue box"?
closed account (jvqpDjzh)
Well, your function returns a reference to a integer, which means an lvalue, which means that it can be modified, and in your case that value will be y. Assigning to your function -1, your are modifying the value of y. Just try to make x greater than y and you will see that x == -1 !
Last edited on
dude..

kindly explain why "y value only modified.."
closed account (jvqpDjzh)
@r 4 raja (15) wrote:
 kindly explain why "y value only modified.."
? What did I do?
@zwilu wrote:
 Well, your function returns a reference to a integer, which means an lvalue, which means that it can be modified, and in your case that value will be y. Assigning to your function -1, your are modifying the value of y. Just try to make x greater than y and you will see that x == -1 !

Your functions is an lvalue, the result of the internal body, that can be modified with this expression: maxref(x,y)=-1;//maxref(x, y) is an lvalue,
//it's on the left of the operator =, that means that its result can be modified!
Last edited on
Topic archived. No new replies allowed.