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

后端 未结 3 1176
死守一世寂寞
死守一世寂寞 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.)

提交回复
热议问题