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

后端 未结 5 889
有刺的猬
有刺的猬 2021-01-04 03:16

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 
u         


        
相关标签:
5条回答
  • 2021-01-04 03:44

    The build-in ! operator converts its argument to bool. The standard specifies that there exists a conversion from any arithmetic type(int, char,.... float, double...) to bool. If the source value is 0 the result is true, otherwise it is false

    0 讨论(0)
  • 2021-01-04 03:45

    You can, !b is equivalent to (b == 0).

    0 讨论(0)
  • 2021-01-04 03:46

    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.)

    0 讨论(0)
  • 2021-01-04 03:51

    The test for int is true for non-zero values and false for zero values, so not is just true for zero values and false for non-zero values.

    0 讨论(0)
  • Originally, in C (on which C++ is based) there was no Boolean type. Instead, the value "true" was assigned to any non-zero value and the value "false" was assigned to anything which evaluates to zero. This behavior still exists in C++. So for an int x, the expressions !x means "x not true", which is "x not non-zero", i.e. it's true if x is zero.

    0 讨论(0)
提交回复
热议问题