Why is there no warning about implicit type conversion?

I finally found out the error in my program caused by the implicit type conversion in the return type. Even with g++ -Wall there are no warnings for this.

I wonder if anyone has the opportunity to quickly detect such meaningless 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; } 
+4
source share
3 answers

This is the correct code. if (i), where i is of type int , is also correct.

n3376 4.12 / 1

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

+3
source

This is a normal type promotion. From the C ++ standard:

bool , char , wchar_t , and signed and unsigned integer types are collective types called integral types

and

A value of type bool can be converted to an rvalue of type int , with false becoming zero and true becoming single.

+1
source

Iddeed, most (all?) Compilers seem conceptually inconsistent when they usually warn of a possible loss of significant digits or accuracy (for example, in the case of conversion to int to char or similar), but make an exception for conversion to bool.

I assume that there are only historical reasons for this.

Many legacy code uses constructs such as

if (number) ... or if (pointer) ...

instead

if (number! = 0) ... or if (pointer! = NULL) ...

In addition, the latter style is often considered too verbose.

The tradition is convenient, it allows you to write compressed code, but it is really error prone. It is not supported (knowingly) in some other languages ​​(e.g. Java).

0
source

All Articles