How to get the compiler to warn that this is an invalid bool?

拜拜、爱过 提交于 2019-12-24 03:51:40

问题


We just got burnt by a typo: "constexpr bool maxDistance=10000;"

Both gcc and clang compile this with no warning.

The real error here is that the variable shouldn't have been of type bool, but should have been an integer type instead.

How can we ensure we get a compiler warning in future?

#include <iostream>

constexpr bool number = 1234;
int main(int argc, char* argv[])
{
    std::cout << number + 10000 << std::endl; // prints 10001.
    return number;
}

The error here is that the variable is declared with the wrong type, however neither clang nor gcc give a warning.

gcc -Wall -std=c++14 test.cpp -lstdc++
clang -Wall -std=c++14 test.cpp -lstdc++

(using gcc 5.4.0 and clang 3.8.0)

Note: I've since learnt about a possible compile flag: -Wint-in-bool-context however this doesn't appear to be implemented in the version I'm using (5.4.0) nor in clang (3.8.0).

Is this the right way to go?


回答1:


You should use direct list initialization syntax, it prohibits narrowing:

constexpr bool number{1234}; // error: narrowing conversion of '1234' from 'int' to 'bool' [-Wnarrowing]



回答2:


I've discovered that gcc has a flag '-Wint-in-bool-context' however this doesn't appear to be implemented in the version I'm using (5.4.0) nor in clang (3.8.0).

Is this the right way to go?



来源:https://stackoverflow.com/questions/58144656/how-to-get-the-compiler-to-warn-that-this-is-an-invalid-bool

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