Confused by use of double logical not (!!) operator

This question already has an answer here:

  • Double Negation in C++ code 14 answers
  • What is “!!” in C? [duplicate] 7 answers

  • It is not as simple as double negation. For example, if you have x == 5 , and then apply two ! operators ( !!x ), it will become 1 - so, it is used for normalizing boolean values in {0, 1} range.

    Note that you can use zero as boolean false, and non-zero for boolean true, but you might need to normalize your result into a 0 or 1, and that is when !! is useful.

    It is the same as x != 0 ? 1 : 0 x != 0 ? 1 : 0 .

    Also, note that this will not be true if foo is not in {0, 1} set:

    !!foo == foo

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
            int foo = 5;
    
            if(foo == !!foo)
            {
                    cout << "foo == !!foo" << endl;
            }
            else
            {
                    cout << "foo != !!foo" << endl;
            }
    
    
    
            return 0;
    }
    

    Prints foo != !!foo .


    It can be used as shorthand to turn foo into a boolean expression. You might want to turn a non-boolean expression into true or false exclusively for some reason.

    foo = !!foo is going to turn foo into 1 if it's non-zero, and leave it at 0 if it already is.


    if foo != 0 , then !!foo == 1 . It is basically a trick to convert to bool.

    链接地址: http://www.djcxy.com/p/73552.html

    上一篇: 标准C(gcc特定功能)?

    下一篇: 使用双逻辑非(!!)运算符困惑