Search code examples
c++pointerscastinglvaluervalue

Casting and pointer casting in C++


Can anyone explain me why this is true:

char *p;
short  i;
long l;

(long *) p = &l ;       /* Legal cast   */
(long) i = l ;          /* Illegal cast */

I know it has something to do with lvalue and rvalue but shouldn't (long *) p be a rvalue?

edit:

sorry it seems I confused myself and others, I asked this while reading "this MDSN" and I was surprised to see this syntax, I see it's a special feature that allows to convert lvalue into lvalue as long as it's the same size.


Solution

  • Neither of these expressions are legal, they should both fail to compile.

    C++11, 5.17.1:

    The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

    5.4:

    Explicit type conversion (cast notation) [expr.cast] 1 The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.

    So both expressions violate these constraints.