Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused by use of double logical not (!!) operator [duplicate]

I have some C++ code that makes extensive use of !!. I'm kinda baffled because as far as I know !! is not a operator on it's own but two ! after each other. So that would mean that !!foo is the same as just foo.

Is there any place and or reason when !! actually makes sense? I was thinking about if it could perhaps have a bit wise meaning? So you first perform some bit wise operation on foo and then ! on the result? But I don't seem to remember ! being used as a bit wise operator and don't seem to find any reference telling me it is either. As far as I can tell ! in only used as a logical operator and in that case

!!foo == foo

like image 499
inquam Avatar asked Apr 24 '13 12:04

inquam


People also ask

What are the 2 logical operators?

Common logical operators include AND, OR, and NOT.

What is logical operators write any two logical operators with example?

Logical Operators/is the logical not operator. && is the logical and operator. It returns TRUE if both of the arguments evaluate to TRUE. This operator supports short-circuit evaluation, which means that if the first argument is FALSE the second is never evaluated.


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

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.

like image 169
Nemanja Boric Avatar answered Sep 27 '22 20:09

Nemanja Boric