Can I use the not operator in C++ on int values?

001 picture 001 · Nov 8, 2010 · Viewed 36k times · Source

Strange question, but someone showed me this, I was wondering can you use the not ! operator for int in C++? (its strange to me).

#include <iostream>
using namespace std;

int main()
{
   int a=5, b=4, c=4, d;
   d = !( a > b && b <= c) || a > c && !b;
   cout << d;
   system ("pause");
   return 0;
}

Answer

kennytm picture kennytm · Nov 8, 2010

Yes. For integral types, ! returns true if the operand is zero, and false otherwise.

So !b here just means b == 0.


This is a particular case where a value is converted to a bool. The !b can be viewed as !((bool)b) so the question is what is the "truthness" of b. In C++, arithmetic types, pointer types and enum can be converted to bool. When the value is 0 or null, the result is false, otherwise it is true (C++ §4.1.2).

Of course custom classes can even overload the operator! or operator<types can be convert to bool> to allow the !b for their classes. For instance, std::stream has overloaded the operator! and operator void* for checking the failbit, so that idioms like

while (std::cin >> x) {   // <-- conversion to bool needed here
  ...

can be used.

(But your code !( a > b && b <= c) || a > c && !b is just cryptic.)