Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits, mostly

Although common practice has been to programmers often use integers and pointers interchangeably in C, pointer-to-integer and integer-to-pointer conversions are implementation-defined

...

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.

See also undefined behavior 24 of Annex J.

Do not convert an integer type to a pointer type if the resulting pointer is incorrectly aligned, does not point to an entity of the referenced type, or is a trap representation.

Do not convert a pointer type to an integer type if the result cannot be represented in the integer type.

These issues arise because the mapping functions for converting a pointer to an integer or an integer to a pointer The mapping between pointers and integers must be consistent with the addressing structure of the execution environment. For Issues may arise, for example, not all machines on architectures that have a flat segmented memory model.

Noncompliant Code Example

The size of a pointer can be greater than the size of an integer, such as in an implementation where pointers are 64 bits and unsigned integers are 32 bits. Because This code example is noncompliant on such implemetnations because the result of converting the 64-bit ptr cannot be represented in the 32-bit integer type, this noncompliant code example has undefined behavior:

Code Block
bgColor#ffcccc
langc
void f(void) {
  char *ptr;
  /* ... */
  unsigned int number = (unsigned int)ptr;
  /* ... */
}

...

Noncompliant Code Example

In this noncompliant code example, the pointer ptr is converted to an integer value. The high-order 9 bits of the number are used to hold a flag value, and the result is converted back into a pointer. This example is noncompliant , for example, on an implementation where pointers are 64 bits and unsigned integers are 32 bits because the result of converting the 64-bit ptr cannot be represented in the 32-bit integer type.

...