Why is the sum of an int and a float an 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 does this happen?
Interestingly, when I explicitly put my compiler into C11 mode, I found that sum
was 4.14. What rules does the C11 standard change that affect the outcome?
What would happen if I compiled the same code using a C++ compiler?
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++.)
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.
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.)