Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

gcc

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.
like image 476
Willi Ballenthin Avatar asked Mar 26 '10 22:03

Willi Ballenthin


3 Answers

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

like image 97
Paul Tomblin Avatar answered Dec 19 '22 11:12

Paul Tomblin


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 */
like image 34
hhafez Avatar answered Dec 19 '22 11:12

hhafez


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

like image 33
Michael Burr Avatar answered Dec 19 '22 10:12

Michael Burr