refrence in c++

Nov 8, 2011 at 9:18pm
#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


Nov 8, 2011 at 10:30pm
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 
Nov 18, 2011 at 2:59pm
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
Nov 18, 2011 at 3:27pm
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;
}

Nov 18, 2011 at 3:49pm
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.
Nov 18, 2011 at 4:20pm
???
Nov 18, 2011 at 4:25pm
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 Nov 18, 2011 at 4:27pm
Nov 20, 2011 at 8:05am
thanx for the reply everone my doubt is cleared..........
Topic archived. No new replies allowed.