Saturday, December 10, 2011

Use of '!!' (double negation) in C programming

In some of the 'C' codes, I saw use of '!!' in expressions. I was just wondering about use of such a redundant operation (since '!!' negated the negation).
In one of the mails in LKML (Linux Kernel Mailing List), I came to know about its significance. The '!!' is used to convert an expression to authentic boolean value.

For example:

int a = 0xFF;
if (!!(a & 0x0F))
    //do something
    //do some other thing

Here (a & 0x0F) resolves to '0x0F' while !!(a & 0x0F) resolves to '1'.
That means use of '!!' results in authentic boolean value i.e. either '0' or '1'.

We can see the same kind of expressions in linux kernel code.

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

In the first case, the expression has to evaluate to any value other than '0' for likely condition to happen. However, may be to reduce side effects or maintain consistency, the precaution would have been taken and expression is converted to authentic boolean value.

It seems redundant for the unlikely condition though.

Please share if you have any alternate thoughts.