为什么没有隐式类型转换的警告? [英] why no warning for implicit type conversion?

查看:201
本文介绍了为什么没有隐式类型转换的警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于找出了我的程序中的一个错误,这是由返回类型上的隐式类型转换造成的。即使使用 g ++ -Wall ,也没有警告。

I finally figured out a bug in my program, which caused by the implicit type conversion on return type. Even with g++ -Wall there is no warning for this.

我想知道是否有快速找出这种无意义的错误?

I wonder if there is someway to quickly find out such mindless errors?

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


推荐答案

if(i) i 的类型 int 也正确。

This is correct code. if (i) where i has type int is correct too.

n3376 4.12 / 1


算术,无范围枚举,指针或指向成员类型的prvalue可以转换为bool类型的
prvalue 。零值,空指针值或空成员指针值将转换为false;
任何其他值将转换为true。

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.

这篇关于为什么没有隐式类型转换的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆