Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Negation in C++

Tags:

c++

boolean

People also ask

What is double negation in C?

In C and C++ the double negation operator can be (and often is) used to convert a value to a boolean. Simply put, if int x = 42 , !! x evaluates to 1. If x = 0 , !!

What does double negation do?

It first negates the result of the expression, then it negates it again. In this way if you had a non-zero number, a string, an object, an array, or anything that's truthy, you'll get true back. Otherwise you'll get false .

How do you negate a double?

Double negatives are created by adding a negation to the verb and to the modifier of the noun (adjectives, adverbs, etc.) or to the object of the verb. I won't (will not) bake no cake. I can't (cannot) go nowhere tonight.

Is double negation possible?

A double negative is a statement which contains two negative words. If two negatives are used in one sentence, the opposite meaning may be conveyed. In many British, American, and other dialects, two or more negatives can be used with a single negative meaning.


It's a trick to convert to bool.


It's actually a very useful idiom in some contexts. Take these macros (example from the Linux kernel). For GCC, they're implemented as follows:

#define likely(cond)   (__builtin_expect(!!(cond), 1))
#define unlikely(cond) (__builtin_expect(!!(cond), 0))

Why do they have to do this? GCC's __builtin_expect treats its parameters as long and not bool, so there needs to be some form of conversion. Since they don't know what cond is when they're writing those macros, it is most general to simply use the !! idiom.

They could probably do the same thing by comparing against 0, but in my opinion, it's actually more straightforward to do the double-negation, since that's the closest to a cast-to-bool that C has.

This code can be used in C++ as well... it's a lowest-common-denominator thing. If possible, do what works in both C and C++.


The coders think that it will convert the operand to bool, but because the operands of && are already implicitly converted to bool, it's utterly redundant.


Yes it is correct and no you are not missing something. !! is a conversion to bool. See this question for more discussion.


It's a technique to avoid writing (variable != 0) - i.e. to convert from whatever type it is to a bool.

IMO Code like this has no place in systems that need to be maintained - because it is not immediately readable code (hence the question in the first place).

Code must be legible - otherwise you leave a time debt legacy for the future - as it takes time to understand something that is needlessly convoluted.


It side-steps a compiler warning. Try this:

int _tmain(int argc, _TCHAR* argv[])
{
    int foo = 5;
    bool bar = foo;
    bool baz = !!foo;
    return 0;
}

The 'bar' line generates a "forcing value to bool 'true' or 'false' (performance warning)" on MSVC++, but the 'baz' line sneaks through fine.