Suppose we have the following code:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint16_t a[] = { 1, 2, 3, 4 };
const size_t n = sizeof(a) / sizeof(uint16_t);
for (size_t i = 0; i < n; i++) {
uint16_t *b = (uint16_t *) ((uint8_t *) a + i * sizeof(uint16_t));
printf("%u\n", *b);
}
return 0;
}
Clearly, casting a
to an uint8_t
pointer is not a violation, so this question is about casting that resulting pointer to an uint16_t
pointer. In my understanding, according to the standard it does violate the strict aliasing rule. However, I am not sure from a practical point of view, since the types of a
and b
are compatible. The only potential violation is b
aliasing the uint8_t
pointer that exists only throughout this one expression. So in my understanding, even if it violates the rule, I would doubt that it can cause undefined behavior. Can it?
Note that I am not saying that this code is meaningful. The question is meant for purely educational purposes regarding the understanding of strict aliasing.
uint32_t a[]; b = (uint32_t*)((uint16_t*)a + i * sizeof(uint32_t)/sizeof(uint16_t))
would be also fine, right? The thing is, the resultinguint16_t
pointer value is properly aligned touint16_t
. – Wayfaring