1

uintptr_t and intptr_t are numerical types big enough to contain pointers, my question is how do they relate to other numerical types when casting toward them. Specifically which types (int, long, long long, short, char, size_t etc.) cant NUM_TYPE be defined as so that the next function does not corrupt the value of n?

intptr_t cast_num(NUM_TYPE n){return (intptr_t) n;}
afiori
  • 465
  • 3
  • 15

1 Answers1

1

The optional types:

intptr_t has a range of at least [-0x7FFF...0x7FFF].

uintptr_t has a range of [0... at least 0xFFFF].


Use INTPTR_MIN, INTPTR_MAX, UINTPTR_MAX from <stdint.h> to form condition code as needed.

intptr_t cast_long(unsigned long n) {
  _Static_assert(UIINTPTR_MAX >= ULONG_MAX, "unsigned long too big"): 
  return (intptr_t) n;
}

Note: Object pointers to/from uintptr_t and intptr_t should be converted through void *. Function pointers may be too big.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256