Changing bytes
suggest changeOnce an object has an effective type, you should not attempt to modify it through a pointer of another type, unless that other type is a character type, char
, signed char
or unsigned char
.
#include <inttypes.h>
#include <stdio.h>
int main(void) {
uint32_t a = 57;
// conversion from incompatible types needs a cast !
unsigned char* ap = (unsigned char*)&a;
for (size_t i = 0; i < sizeof a; ++i) {
/* set each byte of a to 42 */
ap[i] = 42;
}
printf("a now has value %" PRIu32 "\n", a);
}
This is a valid program that prints
a now has value 707406378
This works because:
- The access is made to the individual bytes seen with type
unsigned char
so each modification is well defined. - The two views to the object, through
a
and through*ap
, alias, but sinceap
is a pointer to a character type, the strict aliasing rule does not apply. Thus the compiler has to assume that the value ofa
may have been changed in thefor
loop. The modified value ofa
must be constructed from the bytes that have been changed. - The type of
a
,uint32_t
has no padding bits. All its bits of the representation count for the value, here707406378
, and there can be no trap representation.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents