Search code examples
ccompound-literals

Difference between cast used in Compound literals and that done on a pointer variable?


Consider the following code:

int main()
{ 
    int *p;

    ++((int){5});    //compile without err/warning
    &((int){5});     //compile without err/warning

    ++((char *)p);   //Compile-time err: invalid lvalue in increment
    &((char *)p);    //Compile-time err: invalid lvalue in unary '&'

}

Why do the Compound Literals do not generate errors here?


Solution

  • It is because the "cast" in a compound literal is not a cast at all - it just looks like one.

    A compound literal (which is the complete construction (int){5}) creates an lvalue. However a cast operator creates only an rvalue, just like most other operators.

    This example would be allowed (but useless, just like your int examples):

    ++((char *){(char *)p});
    &((char *){(char *)p});