In C and C++ the double negation operator can be (and often is) used to convert a value to a boolean.
Simply put, if int x = 42
, !!x
evaluates to 1. If x = 0
, !!x
evaluates to 0.
You could argue that it is not readable, but as of the current date I counted more than 5000 instances of this idiom in the Linux kernel. For this reason alone itâs worth being aware of it.
#include <stdio.h>
int main()
{
int x = 42;
// Following statements are equivalent:
printf("x is %d, which is boolean %d.\n", x, !!x);
printf("x is %d, which is boolean %d.\n", x, (x == 0 ? 0 : 1));
printf("x is %d, which is boolean %d.\n", x, x != 0);
// Output: "x is 42, which is boolean 1."
x = 0;
// Following statements are equivalent:
printf("x is %d, which is boolean %d.\n", x, !!x);
printf("x is %d, which is boolean %d.\n", x, (x == 0 ? 0 : 1));
printf("x is %d, which is boolean %d.\n", x, x != 0);
//Output: "x is 0, which is boolean 0."
return 0;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4