lostyzd
lostyzd

Reputation: 4523

why no warning for implicit type conversion?

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

Upvotes: 4

Views: 272

Answers (3)

user396672
user396672

Reputation: 3166

Iddeed, most(all?) compilers seem conceptually inconsistent when they usually warn about possible losing of significant digits or precision (for instance in case of int to char conversion or similar) but make an exception for conversion to bool.

I suppose there are only historical reasons for that.

A lot of legacy code uses constructs like

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

instead of

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

Moreover, the latter style often regarded as too verbose.

The tradition is convinient, allows to write concise code, but it is indeed error prone. It is not supported (consciously) in some another languages (e.g.Java).

Upvotes: 0

Matthias
Matthias

Reputation: 8180

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

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

and:

An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

Upvotes: 1

ForEveR
ForEveR

Reputation: 55897

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

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.

Upvotes: 3

Related Questions