thanks for your answer, this is what I fearing. However, I'm surprised
when you say that the struct value as is accessed as a short, despite
the char * cast: (from 9899:1999 6.5.4 "Preceding an expression by a
parenthesized type name converts the value of the expresion to the named
type").
Now you seem to imply that the aliasing rule only looks at the final
points-to object's effective type, not the expression's lvalue type
implied by the cast or the temporary pointer.
many thanks
-c
Ian Lance Taylor wrote:
Christian BRUEL <christian.bruel@xxxxxx> writes:
From my understanding of the type-punning aliasing rule, the
following
code is correct, and indeed compiles fine with gcc/trunk :
typedef struct {
short a : 16;
short b : 16;
} c;
foo(c t1)
{
char *pt1 = (char*)&t1;
if (*(int*)(pt1))
return 0;
return 1;
}
No, this is not OK in C. The rule is that you may access a stored value
only via a union, or a pointer to a compatible type, or a pointer to a
character type. You You are (presumably) storing the value as short,
and are accessing it as int. That is not OK. The rule is about how you
access the value; passing the address of the value through a char *
pointer does not sanitize it.
gcc's aliasing warnings do their best but they are not intended to catch
every erroneous case.
However if I try to rewrite it using an intermediate cast :
foo(c t1)
{
if (*((int*)((char*)&t1)))
return 0;
return 1;
}
This isn't OK either.
Ian