Inspired by my comment on the recent post: C get element on place without parenthesis , I would like to know if the following code breaks the strict aliasing rule:
#include <stdio.h>
int main(void)
{
int num[3] = { 1, 2, 3 };
printf("num[1] = %d\n", *(int *)((char *)num + sizeof(int)));
return 0;
}
I know that de-referencing a pointer that is type-cast to a different type other than char
is a violation, but here, the original pointer is of type int *
. It is de-referenced after it is cast to char *
then to int *
.
Does this violate the strict aliasing rule?
Quoting C11
, chapter §6.5p7
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
- a type compatible with the effective type of the object
Also
Quoting C11
, chapter §6.5p6
The effective type of an object for an access to its stored value is the declared type of the object, if any....
Emphases mine
Here the effective type of the object pointed by num
is indeed int
and hence it is okay to dereference it with a pointer to int
.