1
int bar(const size_t value) {
  char *d = (char*) value; 
  *d = 'B';
}

int main() {
    char bar = 'A';
    bar((size_t)&d);
}
  1. Is using size_t to emulate a void pointer type legal? Why?

  2. What benefits/drawbacks does it have?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
HighPredator
  • 790
  • 4
  • 21

1 Answers1

3

For data pointers, round trip from a pointer to an integer types back to the original pointer type is well defined as long as the integer type is wide enough to hold the pointer without loss.

size_t has been defined to hold object size. They are usually big enough to hold a pointer representation but that is not guaranteed and they were implementations where the assumption didn't hold.

uintptr_t and intptr_t are integer types defined to be wide enough to hold a pointer without loss.

For function pointers, I'm aware of no such guarantee.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143