caddress-operator

How &(*x) works? Details below


int a = 1;
int* x = &a;
//-> &*x equal to &a

If the pointer x has the adress of a and *x points to a's value, compiler couldn't know that *x was referring to exactly a, it could only know a's value if I pass *x.

But turns out it knows. So how does this work? does compiler pass the adress too or is it just cancelling * when I put & like &*x compiles as if its just like x or the other way?


Solution

  • 1, a, x, *x are all expressions.

    Some expressions have addresses (they are called "lvalues"), others don't (they are called "rvalues").

    1 is a rvalue, it doesn't have an address. So &1 doesn't compile.

    a is an lvalue, so it does have an address.

    *x is also an lvalue, so it too has an address. This is just how the language works. It could've been made differently (*x could've been an rvalue), but it was made an lvalue, because it's convenient to have the address available.

    For the operator &, there's no difference between a and *x, since both have the same value category (both are lvalues).

    You seem to have assumed (even without knowing the terms) that only variable names are lvalues (only they have addresses), which is not the case.