Pointer to integer conversion in C

Viewed 181

C11 6.3.2.3/6 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.

The quote above, says that if value of a pointer expression after conversion to integer type is representable by integer its okey to convert it. But there is something bothers me. I looked to standard but i couldn't find how the pointer to int conversion takes place.

Let's say we have a pointer object, which pure binary interpretation of it equals to 0x100. If we convert it to a unsigned integer of enough precision, can we say that expression's value after conversion will be equal to 0x100 due to standard?

Or let me put it this way, is there a convention on how pointer objects represented on memory?

1 Answers

As the text you cite states, the result is implementation-defined. Per C 3.4.1, this is:

unspecified behavior where each implementation documents how the choice is made.

Thus, the C implementation you are using (primarily the compiler) is required to document how the result is determined.

In implementations with “flat” virtual address spaces, where each pattern of bits within a certain range represents an address, it is common to simply reinterpret the bits as a binary numeral. So the address 1 0000 0000 would be converted to the number 256.

However, implementations with some form of base-and-offset or segment-and-offset addressing might form an integer with the base in some bits and the offset in another, and there are other possibilities.

Related