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?

+3


source to share


3 answers


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 to long double

    .
  • Otherwise, if any operand double

    , the other must be converted to double

    .
  • Otherwise, if any operand float

    , the other must be converted to float

    .
  • Otherwise, integral promotions must be performed on both operands.
+5


source


Because when you multiply int

by a, double

you get double

.



+2


source


The C and C ++ compilers always support basic numeric types for the most general type included in an expression. Thus, any expression containing two values int

gives int

, but if any of the operands double

, then the value of the expression will also be double

.

+1


source







All Articles