Search code examples
cdereference

Why does *(&identifier)=value works in C?


For example,

int x = 10;
*(&x) = 20;
printf("%d \n",x); // output is 20

According to ISO C11-6.5.3.2 paragraph 4, it says that

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

Since the operand &x is neither function designator nor object designator (it is a pointer to type int), I expected undefined behaviour but it works just fine! What am I missing?


Solution

  • Let me parse it for you:

    int x = 10;
    *(&x) = 20;
    
    • * == the asterisk operator
    • &x == the operand (of the asterisk operator)

    If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.

    The operand (&x == address of x where x is an int) points to an object of type int.

    => The result is an lvalue designating x (x==the object).

    If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’.

    The operand has type pointer to int, therefore the result has type int.