What does !!(x) mean in C (esp. the Linux kernel)?

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:

  • How does logical negation work in C?
  • Double Negation in C++ code.

!!(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.


It's not so much a language syntax but a common shorthand for converting a char or int into quasi-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 */

!!(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).