c++ - 为什么没有隐式类型转换的警告?

标签 c++ gcc type-conversion

我终于在我的程序中找出了一个错误,它是由返回类型的隐式类型转换引起的。即使使用 g++ -Wall 也不会对此发出警告。

不知道有没有办法快速找出这种无脑错误?

#include <iostream>

// return type should be int, but I wrote bool by mistake
bool foo(int x) {
  return x;
}

int main() {
  for (int i = 0; i < 100; ++i) {
    std::cout << foo(i) << std::endl;
    // 0 1 1 1 1 1  ..
    // should be 0 1 2 3 4 ...
  }

  return 0;
}

最佳答案

这是正确的代码。如果 (i) i 的类型 int 也是正确的。

n3376 4.12/1

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

关于c++ - 为什么没有隐式类型转换的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15135196/

相关文章:

c++ - 在 Qt C++ 上运行 dlib

c - GCC 提示非标准调用约定 "ZEND_API"

java - double a = a + int b 和 int a += double b 有什么区别?

c++ - 静态变量定义时间 C++

C++ 转换问题

c++ - 复合文字并通过GCC在C++中通过引用传递?

java - 在Delphi上读取JAVA生成的二进制文件

c++ - 对话框不正确地重绘其背景

C++ 将 char 添加到 char[1024]

assembly - 英特尔 x86_64 程序集 : What is good way to convert 32bit integer to 64bit int?