tags:

views:

298

answers:

3

I've been reading through the Linux kernel (specifically, 2.6.11). I came across the following definition:

#define unlikely(x)     __builtin_expect(!!(x), 0)

(from linux-2.6.11/include/linux/compiler.h:61 lxr link)

What does !! accomplish? Why not just use (x)?

See also:

+11  A: 

!!(x) forces it to be either 0 or 1. 0 remains 0, but any non-zero value (which would be 'true' in a boolean context) becomes 1.

Paul Tomblin
That should be 0 or **1**.
R Samuel Klatchko
This is a really neat trick - going to remember it. +1.
Ninefingers
It's really not necessary in this case since we expect the result to be 0. It's really only necessary for the `#define likely(x) __builtin_expect(!!(x), 1)` to ensure that true is 1. It's likely only included in the `unlikely` definition for symmetry.
Chris Lutz
invariant
cool little trick!
Lazer
IMO `x != 0` expresses it more clearly.
jamesdlin
+6  A: 

Its not so much a language syntax but a common shorthand for converting a char or int into qausi-boolean.

In C logical operations such as == && ! and so on can act on int, char etc, as there is no boolean type, however according to the standard they are guaranteed to return 0 for False and 1 for true.

So for example if you have

int x = 5;

you can force it to convert to a "boolean" type (there is no boolean type in C hence the quotes" you do

x = !x; /* !5 which gives 0 always */
x = !x; /* which gives 1 always */
hhafez
+1  A: 

!!(x) is equivalent to (x) != 0 (unless some very oddball operator overloading is going on in C++).

The fact that it's not obvious what !!(x) is doing is a probably a good reason to use (x) != 0. Unless you want to be an elite kernel hacker.

See this closed question (if it's still around) for a discussion of the merits of !! (maybe that question will be be reopened, since this question indicates that it has some value).

Michael Burr
It's "not obvious" what `!!(x)` does for half a second the first time you see it. After you see it and either a) think about it for a bit or b) ask someone else, you'll recognize what the `!!` "operator" does quite quickly.
Chris Lutz
@Chris - if it's a common idiom in your shop, it's probably OK to use it. On the other hand, I come across `!!(x)` infrequently enough that I have to pause for a moment to grok it. I don't have to cipher for a moment about what `(x) != 0` means. Not a huge deal, but I see little to recommend `!!(x)` over `(x) != 0`.
Michael Burr
@Michael - Fair enough. I rather like the way it looks, but there isn't really a compelling argument for using it over `(x) != 0` (unless you need to rely on some objects overloading `!` to evaluate them in boolean contexts).
Chris Lutz