No warning for implicit cast of bool to floating type?

泪湿孤枕 提交于 2021-02-07 13:18:28

问题


Looks like this snippet compiles in clang without warning, even with -Weverything:

double x;
...
if (fabs(x > 1.0)) {
   ...
}

Am I missing something? Or do the compiler and C++ standard think that casting bool to double is something that makes sense?


回答1:


This is a consequence of making bool an integral type. According to C++ standard, section 3.9.1.6

Values of type bool are either true or false (Note: There are no signed, unsigned, short, or long bool types or values. — end note) Values of type bool participate in integral promotions. (emphasis is added)

This makes values of bool expressions to be promoted to float in the same way the ints are promoted, without a warning, as described in section 4.5.6:

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

EDIT : Starting with C++11 fabs offers additional overloads for integral types, so the promotion goes directly from bool to int, and stops there, because an overload of fabs is available for it.



来源:https://stackoverflow.com/questions/23874077/no-warning-for-implicit-cast-of-bool-to-floating-type

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