GCC:禁止隐式bool->int转换

dauxcl2d  于 2023-06-23  发布在  其他
关注(0)|答案(6)|浏览(178)

是否有任何gcc标志禁止隐式boolint转换?
我想用这段代码得到任何警告:

  1. void function( int value, bool flag ) { }
  2. int main()
  3. {
  4. int a = 123;
  5. bool flag = true;
  6. //oops, a common mistake
  7. function( flag, a );
  8. }
a11xaf1n

a11xaf1n1#

作为解决方法,在C++11中,您可以删除其他可能的重载:

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

yyhrrdl82#

回答你的问题:不,在这种情况下没有gcc标志来发出警告。你的问题在gcc邮件列表上讨论了好几次。例如here
编译器没有检查这一点的主要原因在于,否则每个语句(如if( intval ))也会引发警告。

8ljdwjyq

8ljdwjyq3#

在C中,你可以将一个值 Package 在一个只支持一种类型的泛型选择中:

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

这会出错(GCC 4.9),但如果用truex替换1,编译时不会出错。
举个例子:

  1. #include <stdbool.h>
  2. void function( int value, bool flag ) { }
  3. #define function(V, F) function(V, _Generic(F, bool:F))
  4. int main() {
  5. int a = 123;
  6. bool flag = true;
  7. function( flag, a ); // error: '_Generic' selector of type 'int' is not compatible with any association
  8. }
展开查看全部
kqlmhetl

kqlmhetl4#

clang-tidy会警告您,或者更好的是,将此设置为您的错误。
这个测试是readability-implicit-bool-conversion。在早期版本的linter中,测试被命名为readability-implicit-bool-cast

zfciruhq

zfciruhq5#

使用 Package 器类:

  1. class Boolean
  2. {
  3. bool flag;
  4. public:
  5. explicit Boolean(bool something){}
  6. bool getValue() const {return flag;}
  7. void setValue(bool a) {flag = a;}
  8. };
  9. void function(int value,Boolean flag ) { }
  10. int main()
  11. {
  12. int a = 123;
  13. Boolean flag(true);
  14. function( flag, a ); // fails! Boolean isn't a int value :)
  15. }
展开查看全部
wko9yo5t

wko9yo5t6#

使用kernel. h中question min宏中的思想,您可以使用gcc的typeof

  1. #include <stdbool.h>
  2. #define function(x, y) do { \
  3. __typeof(x) tmpone = (x); \
  4. int tmptwo = 0; \
  5. (void) (&tmpone == &tmptwo); \
  6. fx((x), (y)); \
  7. } while (0)
  8. void fx(int value, bool flag) {
  9. (void)value;
  10. (void)flag;
  11. }
  12. int main(void) {
  13. int a = 123;
  14. bool flag = true;
  15. function(a, flag);
  16. function(flag, a); // oops, a common mistake
  17. }
展开查看全部

相关问题