GCC:禁止隐式布尔>整数转换

GCC: Forbid implicit bool->int conversion

本文关键字:gt 整数 转换 布尔 禁止 GCC      更新时间:2023-10-16

是否有禁止隐式boolint转换的gcc标志?

我想用这个代码得到任何警告:

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

作为一种变通方法,在C++11中,您可以删除其他可能的重载:

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

要回答您的问题:不,在这种情况下没有发出警告的gcc标志。你的问题在gcc邮件列表上讨论了好几次。例如:

编译器不检查这一点的主要原因在于,否则像if( intval )这样的每个语句也会引发警告。

在C中,您可以将值包装在只支持一种类型的泛型选择中:

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

这会出错(GCC 4.9),但如果将1替换为truex,则编译时不会出现任何问题。

举个例子:

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

clang整洁会警告您,甚至更好的是,让这成为一个错误。

这方面的测试是可读性隐式布尔转换。在早期版本的linter中,该测试被命名为readability-implicit-bool-cast

使用包装类:

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 :)
}

使用kernel.h中问题min宏中的思想,可以使用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
}