Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an int's own address to its value

Tags:

c++

c

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  
like image 912
Yuval Avatar asked Nov 11 '13 19:11

Yuval


People also ask

How do you assign an address to a variable?

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.

Is the value of a pointer an address?

An address is a type of pointer value, but pointer values don't point at values; they point at objects or functions.

How do I print an address value?

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.


1 Answers

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."

like image 168
ouah Avatar answered Oct 08 '22 12:10

ouah