Search code examples
c++cundefined-behaviorobject-construction

Assigning an int's own address to its value


Is the following code undefined behavior, implementation defined or defined by the standard? I couldn't find any reference regarding assigning an integer to its own address.

volatile int x = (int)&x;

This code gets translated to:

lea         eax,[ebp-4]  
mov         dword ptr [ebp-4],eax 

Solution

  • In C, using x in both the declaration and the initialization is fine:

    (C99, 6.2.1p7) "[...] Any other identifier has scope that begins just after the completion of its declarator."

    The result of the conversion of the pointer to the integer is implementation-defined and can be undefined behavior:

    (C99, 6.3.2.3p7) "Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type."