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

廉价感情. 提交于 2020-01-02 02:22:10

问题


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;
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/28886226/what-is-the-type-of-auto-var-condition-1-1-0-in-c11-is-it-double-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!