Comparing double to an int

﹥>﹥吖頭↗ 提交于 2021-02-04 19:09:45

问题


While reading the book Programming Principles and Practice Using C++, in Chapter 3 it sates that we can;t directly compare a double to an int. However, when I tested it out on Visual Studios, it was running fine with no errors? What does he mean by not being able to compare double to an int. Later, he explains that C++ provides an indirect way. Does he mean implicit conversion?


回答1:


C++ has a sets of built-in operators defined in [over.built]. The behavior of the equality operator is defined in [expr.eq], in particular:

6 If both operands are of arithmetic or enumeration type, the usual arithmetic conversions are performed on both operands; each of the operators shall yield true if the specified relationship is true and false if it is false.

And usual arithmetic conversions implies:

(1.3) Otherwise, if either operand is double, the other shall be converted to double.

So if you compare an int with a float, a double or a long double, you get implicit conversions from int to float, double or long double.




回答2:


Yes, there is an implicit conversion.

Consider the following program:

bool f()
{
    return 3 == 3.0;
}

If you look at the AST generated by Clang then you see where the implicit conversion is done. Clang calls it an ImplicitCastExpr:

  `-BinaryOperator <col:12, col:17> 'bool' '=='
    |-ImplicitCastExpr <col:12> 'double' <IntegralToFloating>
    | `-IntegerLiteral <col:12> 'int' 3
    `-FloatingLiteral <col:17> 'double' 3.000000e+00


来源:https://stackoverflow.com/questions/50254409/comparing-double-to-an-int

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