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

后端 未结 3 1140
死守一世寂寞
死守一世寂寞 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:22

    It's rather simple really.

    In old versions of C (before C99), you could write something like

    auto n = 3;
    

    and n would be an int type with the value 3. You could also write

    auto n = 3.14f;
    

    and n would still be an int type, with a value 3.

    This was called implicit int and K & R made it quite famous.

    So can you see that

    auto sum = d + i;
    

    merely assigns the float type d + i to sum which is an implicit int.

    Hence the answer 4.

    In newer versions of C (C99 onwards), implicit int was dropped.

提交回复
热议问题