Why is the sum of int and float int?

Consider the following code:

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

According to cppreference.com , i should be converted to float when it is added to d . However, when I actually run the code, I find that sum is 4. Why is this happening?

Interestingly, when I explicitly put my compiler in C11 mode, I found that sum is 4.14. What rules does the C11 standard affect the outcome?

What happens if I compile the same code using the C ++ compiler?

+43
c ++ c type-conversion
Jul 31 '17 at 12:30
source share
3 answers

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

But in C, up to C90, and such a standard may well be your default C compiler, it is assigned the int type, giving 4, since int is the default type for a variable with automatic storage time. Starting with C99, compilation will fail because the implicit int has been revoked, although compilers can still resolve this with a warning.

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

+127
Jul 31 '17 at 12:34 on
source share

It is pretty simple.

In older versions of C (before C99), you can write something like

 auto n = 3; 

and n will be of type int with a value of 3. You can also write

 auto n = 3.14f; 

and n will still be int , with a value of 3.

This was called an implicit int, and K and R made it pretty famous.

So you can see that

 auto sum = d + i; 

just assigns a float type d + i sum , which is an implicit int .

Therefore, the answer is 4.

In newer versions of C (C99 onwards), the implicit int has been removed.

+5
Aug 01 '17 at 18:32
source share

On 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 C, auto is a keyword to indicate the duration of storage. 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. This is why the auto keyword is hardly ever used.

The auto keyword is useless in the C language. This is because the C language existed before the C language, in which this keyword was necessary to declare local variables. (B was developed at NB, which became C.)

+2
Aug 01 '17 at 20:24
source share



All Articles