Why is the sum of an int and a float an int?

后端 未结 3 1133
死守一世寂寞
死守一世寂寞 2021-01-31 14:44

Consider the following code:

float d  = 3.14f;
int   i  = 1;
auto sum = d + i;

According to cppreference.com, i should be converte

3条回答
  •  执笔经年
    2021-01-31 15:20

    In C (and C++), 3.14f + 1 is a float type due to type promotion of int to float.

    But in C, up to and including C90, and such a standard may well possibly be your C compiler default, this is assigned to an int type, yielding 4, since int is the default type for a variable with automatic storage duration. From C99 onwards, compilation will fail as implicit int was withdrawn, although compilers might still permit it, with a warning.

    (In C++11 and later, auto instructs the compiler to deduce the type. sum will be a float with value 3.14f + 1. Compiling as C++98 or C++03 may still work, but generate a warning about C++11 extensions. This is what clang does, for example. This re-defining of auto in C++11 represents another material divergence between C and C++.)

提交回复
热议问题