How does the compiler decide which value to give to auto?
First, I understand that this is a very simple question. I'm just looking for a technical explanation of why the compiler decides to make the following variable with an automatic double over int type specifier:
int value1 = 5;
double value2 = 2.2;
auto value3 = value1 * value2;
I know the compiler will infer the double type for value3 from the initialized value, but why exactly this?
source to share
auto
variable types are defined in terms of template type subtraction. Like this:
template<typename T>
void f(T t);
f(value1 * value2); // will call f<double>()
The reason is value1 * value2
giving double
, not int
because the rules of arithmetic conversion allow converting int
to double
(the inverse is also an implicit conversion, but not an arithmetic conversion). When you use operators on built-in types, "normal arithmetic conversions apply."
Here's the rule found in section 5 (Expressions) of the Standard:
Many binary operators that expect operands of an arithmetic or enumeration type cause conversions and give similar results. The goal is to get a generic type, which is also the type of the result. This pattern is called regular arithmetic conversions, which are defined as follows:
- If any of the operands is of a scoped enumeration type, no conversions are performed; if the other operand is not of the same type, the expression is ill-formed.
- If any of the operands is of type
long double
, the other must be converted tolong double
.- Otherwise, if any operand
double
, the other must be converted todouble
.- Otherwise, if any operand
float
, the other must be converted tofloat
.- Otherwise, integral promotions must be performed on both operands.
source to share