Peaceful
Peaceful

Reputation: 480

double negation to check against not NULL

I have been seeing people writing code like

SomeType c=....

    if(!!c)
    {
     ....
    }

in what circumstance, would it be difference from

if (c)
{
   .....
}

Upvotes: 3

Views: 394

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308206

I've found that the following generates a warning in Microsoft Visual C++:

int i = GetSomeValue();
bool b = (bool) i;

warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

My intent is clear but the compiler insists on generating the warning. If I use the double negation then the warning goes away.

int i = GetSomeValue();
bool b = !!i;

Upvotes: 0

Drew Dormann
Drew Dormann

Reputation: 63775

This practice originates from the C language. Before C had a boolean type.

When c is 0, !!c is also 0.

When c is any other value, !!c is always 1.

This converts c into a true 2-state boolean. Testing expressions like ( !!bool1 == !!bool2 ) or ( !!bool3 == TRUE ) will give the expected result, even if these values are different bitwise representations of "true".

Upvotes: 4

Related Questions