Dev Notes

Software Development Resources by David Egan.

Double Negation Operator Convert to Boolean in C


C, C++
David Egan

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;
}

comments powered by Disqus