Hacker News new | past | comments | ask | show | jobs | submit login

I should have written "AS ACTUALLY STORED" to be clear. You store an int into memory. That memory happens to be described as a char array, but you stored an int as an int. It's an int. It will always be an int, and you can only legitimately interpret it as an int. (Had you stored to key[0] in the normal way then the value would have been be stored as a char instead.)

Reading it out as a long or float would be prohibited by aliasing rules, even if those types happen to be the same size. When you do "if(key[0] != 42)" you are reading out the value in key[0] as char, which is OK, but the content is undefined. You can't legitimately compare an undefined value with 42.

There is a special exception for char. You don't violate the aliasing rules when you load part of the int as a char. This special exception is very limited. It's for implementing functions like memcpy. (but not of that name, since "memcpy" is reserved)

The special exception doesn't make the data meaningful when loaded as char. The bits could be in any order. When you load part of an int into a char, the only legitimate thing you can do with it is to store it as if doing a memcpy.

Depending on how you read the C standard, you might even need an unsigned char to avoid trap representations. People argue this both ways.

That all said, not even gcc is this cruel.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: