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
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.
An address is a type of pointer value, but pointer values don't point at values; they point at objects or functions.
You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With