Click here to Skip to main content
15,041,025 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello everyone.
why in below program, output is 2.5?

float x = 2.5;
float &ref = x;
float *p1;
p1 = &ref + 2;
++(*p1);
cout << ref;
Posted
Comments
   
I'm just curious: what would you expect? :-)
—SA

1 solution

This is because you never modified the value referenced by ref, so, at the end, you see the value you assigned by the moment when you initialized ref.

You probably have been confused by your manipulations with p1. Yes, if it was initialized with p1 = &ref, you would have ref == 3.5; but, by some weird reason, you added 2 to the pointer, that is, pointed the memory area behind x (which is, by the way, is quite unsafe).

SA
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900