3 ms·
1 int x = 10; 2 &x = 20; // this doesn't work 3 * (&x) = 20; // this does work Why does line 2 &x not work but line 3 does? Because &x returns a pointer, a n
by dllthomas 14y ago
1 int x = 10;
2 &x = 20; // this doesn't work
3 * (&x) = 20; // this does work
Why does line 2 &x not work but line 3 does? Because &x returns a pointer, a number representing a memory address. This is an important distinction. A pointer doesn’t hold a memory address, it holds a number that represents a memory address.
=======
No, that is not why. Note that the following does work:
int * x = 0;
and the following works, though typically yields a warning:
int * x = 20;
Line 2 fails because & doesn't give back an l-value.
- deleted 14y ago[deleted]
- dllthomas 14y agoMy point is that pointer-or-not is irrelevant and muddies the issue. The problem is entirely that it's not an l-val.
- denniskubes 14y agoI can agree on that. The point I was trying to make is that &x would return a number not an assignable memory location. The reason it isn't an lvalue is because it doesn't return a memory address the way a variable assignment or dereference would. I was probably a bit confusing in what I was trying to say.
- JoshTriplett 14y agoIt absolutely does return a memory address; it even has the type of a memory address ("int *"). You just can't write to it because it doesn't live in a writable location (an lvalue), for the same reason you can't write: (x + 1) = 12 because (x+1) doesn't live in a writable location.
- mikeash 14y agoIt is quite confusing, because it implies that this is equivalent and equivalently wouldn't work: int *ptr = &x; ptr = 20; The rvalue/lvalue distinction is completely unrelated to pointers, holding memory addresses versus numbers representing memory addresses, etc. The & operator simply doesn't give you an lvalue, like most operators in C, and this has nothing to do with addresses, pointers, or anything of the like
- denniskubes 14y agoAfter rereading it a couple times I think you and others were right. I was trying to say something that in the end muddied issue. I have removed the section on r-value and l-values.