Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition checking: if(x==0) vs. if(!x)

Tags:

c++

What's the differences of if(x==0) vs. if(!x)? Or are they always equivalent? And for different C++ build-in types of x:

  • bool
  • int
  • char
  • pointer
  • iostream
  • ...
like image 421
herohuyongtao Avatar asked Jan 10 '14 07:01

herohuyongtao


1 Answers

Assuming there is a conversion from a type to something that supports if (x) or if (!x), then as long as there isn't a DIFFERENT conversion for operator int() than opterator bool(), the result will be the same.

if (x == 0) will use the "best" conversion, which includes a bool or void * converter. As long as there is any converter that can convert the type to some "standard type".

if(!x) will do exactly the same, it will use any converter that converts to a standard type.

Both of these of course assume the converter function isn't a C++11 "don't default convert".

Of course, if you have a class like this:

class
{
   int x;
  public:
   bool operator bool() { return x != 0; }
   int operator int() { return x == 0; } 
}; 

then if (x == 0) will do if ( (x == 0) == 0) and if (!x) will will do if (! (x != 0), which isn't the same. But now we're really TRYING to make trouble, and this is VERY BADLY designed code.

Of course, the above example can be made to go wrong with any operator int() that doesn't result in false for x == 0 and true for all other values.

like image 136
Mats Petersson Avatar answered Sep 25 '22 17:09

Mats Petersson