Reputation: 5261
GCC's documentation says that -Wstrict-aliasing=3
is the most accurate level and that lower levels are more likely to give false positives.
I believe the following examples all violate the strict aliasing rule:
float violate1(float a_float)
{
float * f_data(&a_float);
int * i_data((int *)f_data);
int value(*i_data);
return value + a_float;
}
float violate2(float a_float)
{
int * i_data((int *)&a_float);
int value(*i_data);
return value + a_float;
}
float violate3(float *f_data)
{
int * i_data((int *)f_data);
int value(*i_data);
return value + *f_data;
}
Yet g++ only gives warnings for them all when -Wstrict-aliasing=1
is used.
With -Wstrict-aliasing=3
no warnings are issued: https://godbolt.org/g/aox2S1
Are the examples in fact not violations or is it that GCC's warnings are not a reliable indication of violations?
Upvotes: 1
Views: 67
Reputation: 21160
The strict-aliasing rule is stated in very clear terms from [basic.lval]
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:
- the dynamic type of the object [...]
This would mean violate1
and violate2
is the same thing and is necessarily a violation.
An object pointer can be casted to and from another arbitrary object pointer type, the result is the original pointer. In violate3
, if f_data
is an int*
previously casted to float*
, there would be no violation with *i_data
, but then it would be a violation at *f_data
Upvotes: 3