GCC: Disallow implicit conversion bool-> int

Is there any gcc flag prohibiting the implicit conversion of "bool → int"?

I want to get a warning with this code:

void function( int value, bool flag ) { } int main() { int a = 123; bool flag = true; //oops, a common mistake function( flag, a ); } 
+6
source share
6 answers

As a workaround in C ++ 11, you can remove other possible overloads:

 template <typename T> void function(int, T) = delete; 
+3
source

To answer your question: no, there is no gcc flag to issue a warning in this case. Your issue has been discussed several times on the gcc mailing list. For example here :

The main reason this is not checked by the compiler is because otherwise, every statement like if( intval ) also raised a warning.

+2
source

In C, you can wrap a value in a universal choice that only supports one type:

 #include <stdbool.h> #include <stdio.h> bool x = true; int y = _Generic(1, bool:2); int main(void) { printf("%d\n", y); } 

These errors (GCC 4.9), but will compile without complaint if you replace 1 with true or x .

So for your example:

 #include <stdbool.h> void function( int value, bool flag ) { } #define function(V, F) function(V, _Generic(F, bool:F)) int main() { int a = 123; bool flag = true; function( flag, a ); // error: '_Generic' selector of type 'int' is not compatible with any association } 
+2
source

Use the shell class:

 class Boolean { bool flag; public: explicit Boolean(bool something){} bool getValue() const {return flag;} void setValue(bool a) {flag = a;} }; void function(int value,Boolean flag ) { } int main() { int a = 123; Boolean flag(true); function( flag, a ); // fails! Boolean isn't a int value :) } 
+1
source

Using the idea in the min macro question in kernel.h , you can use gcc typeof

 #include <stdbool.h> #define function(x, y) do { \ __typeof(x) tmpone = (x); \ int tmptwo = 0; \ (void) (&tmpone == &tmptwo); \ fx((x), (y)); \ } while (0) void fx(int value, bool flag) { (void)value; (void)flag; } int main(void) { int a = 123; bool flag = true; function(a, flag); function(flag, a); // oops, a common mistake } 
0
source

clang-tidy will warn you or even better make a mistake for you.

The test for this is readability-implicit-bool-conversion . In earlier versions of linter, the test is called readability-implicit-bool-cast .

0
source

Source: https://habr.com/ru/post/982980/


All Articles