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

后端 未结 3 864
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 07:49

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)         


        
相关标签:
3条回答
  • 2020-11-30 08:06

    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 */
    
    0 讨论(0)
  • 2020-11-30 08:10

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

    0 讨论(0)
  • 2020-11-30 08:19

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

    0 讨论(0)
提交回复
热议问题