Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› C Syntax Hacks

C Syntax Hacks

C Programming Tricks

C syntax hacks:

 
 /* equivalent to (x ? 1 : 0) */
 int y = !!x;
 

Another one of the "don't try this at home" C syntax hacks. Evaluates to 1 if x is non-zero; evaluates to 0 if x is 0. This example llustrates the difference between ~ (bitwise NOT) and ! (logical NOT). While ~~x is x, the result of ! is 1 or 0; so double application of ! "maps" all non-zero numbers to 1. For example, in the following expression

 int count = !!x + !!y + !!z;
 count is assigned the number of non-zero variables in {x, y, z}. 
 


Partners