Do I have a gcc optimization bug or a C code problem?

前端 未结 9 2107
借酒劲吻你
借酒劲吻你 2021-02-06 00:57

Test the following code:

#include 
#include 
main()
{
    const char *yytext=\"0\";
    const float f=(float)atof(yytext);
    siz         


        
9条回答
  •  礼貌的吻别
    2021-02-06 01:32

    This is no longer allowed according to C99 rules on pointer aliasing. Pointers of two different types cannot point to the same location in memory. The exceptions to this rule are void and char pointers.

    So in your code where you are casting to a pointer of size_t, the compiler can choose to ignore this. If you want to get the float value as a size_t, just assign it and the float will be cast (truncated not rounded) as such:

    size_t size = (size_t)(f); // this works

    This is commonly reported as a bug, but in fact really is a feature that allows optimizers to work more efficiently.

    In gcc you can disable this with a compiler switch. I beleive -fno_strict_aliasing.

提交回复
热议问题