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

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

    In some compilers, files with a .c extension are compiled as C, not C++.

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

    compiled as:

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

    In the C language, auto is a keyword for specifying a storage duration. When you create an auto variable it has an “automatic storage duration”. We call these objects “local variables”. In C, all variables in functions are local by default. That’s why the keyword auto is hardly ever used.

    The auto keyword is useless in the C language. It is there because before the C language there existed a B language in which that keyword was necessary for declaring local variables. (B was developed into NB, which became C.)

    0 讨论(0)
  • 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++.)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题