refrence in c++

#include<stdio.h>
#include<conio.h>
int main(void)
{
clrscr();
int x=100;
int&y=x;
int&a=x;
printf("%d%d%d",x,y,a);
x++;
y++;
a++;
printf("%d%d%d",x,y,a);
while(!kbhit());
return 0;
}
output
100 100 100

103 103 103

why it is so?
it works on both increment and decrement operators


y and a are different names for the variable x. There is only one variable; y and a are other names you can use to mean the exact same variable.

1
2
3
x++; // adjust the value of x
y++; // adjust the value of y, which is just another name for x, so adjust the value of x
a++; // adjust the value of a, which is just another name for x, so adjust the value of x 
thanx for the reply sir ...........

i am not completly satisfy with your ans......a/c to u

x++ //adjust the value of x then there should be increment in the value of x by 1

y++ //adjust the value of y, which is just another name for x so adjust the value of y by 2

in the same way a++ is adjust the value of y which just another name for x so increment in the value of y will be 3

but here scenerao is diffrent.......

sir please clear the doubt
Read the code as this...

int main(void)
{
clrscr();
int x=100;
int x=x;
int x=x;
printf("%d%d%d",x,x,x);
x++;
x++;
x++;
printf("%d%d%d",x,x,x);
while(!kbhit());
return 0;
}

closed account (1vRz3TCk)
JAI SINGH,

Effectively you have this:
          +-----+
X = ----> | 100 |
     |    +-----+
Y = -+
     |
A = -+

Three names for one value.
Incrementing any of the names will increment the one value.
Reading any of the names will read the one value.
???
but here scenerao is diffrent......


No, it isn't different. What I said is exactly what happened.

y++ //adjust the value of y, which is just another name for x so adjust the value of y by 2

What are you talking about? That's nonsense. y++ means increase the value of y by one. Not by two. The value of y was ALREADY increased when we did x++, because y is just another name for x. y and x mean the exact same object in the exact same piece of memory.



Last edited on
thanx for the reply everone my doubt is cleared..........
Topic archived. No new replies allowed.