Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type of "auto var = {condition} ? 1 : 1.0" in C++11? Is it double or int?

In C++11 what are the types of x and y when I write this?

int main()
{
    auto x = true ? 1 : 1.0;
    auto y = false ? 1 : 1.0;
    std::cout << x << endl;
    std::cout << y << endl;
    return 0;
}
like image 843
wefwefa3 Avatar asked Mar 05 '15 19:03

wefwefa3


2 Answers

The type is going to be double, because it's the common type of the literals 1 and 1.0.

There's a simple way to test that using typeid :

#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
    auto x = true ? 1 : 1.0;
    cout << typeid(x).name() << endl;
    return 0;
}

This outputs d on my version of GCC. Running echo d | c++filt -t then tells us that d corresponds to the type double, as expected.

like image 148
tux3 Avatar answered Nov 13 '22 19:11

tux3


According to the description of the conditional operator in the C++ Standard (5.16 Conditional operator)

6 Lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the second and third operands. After those conversions, one of the following shall hold:

— The second and third operands have arithmetic or enumeration type; the usual arithmetic conversions are performed to bring them to a common type, and the result is of that type.

And (5 Expressions)

10 Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

— Otherwise, if either operand is double, the other shall be converted to double.

In the both usages of the conditional operator one of operands is floating literal having type double - 1.0 (the C++Standard: The type of a floating literal is double unless explicitly specified by a suffix.)

auto x = true ? 1 : 1.0;
auto y = false ? 1 : 1.0;

So the other operand also will be converted to type double and the result of expressions has type double.

like image 5
Vlad from Moscow Avatar answered Nov 13 '22 21:11

Vlad from Moscow