[C/C++] Tips and Memos

Language/C&C++ 2010.11.12 17:15

Boolean to integer - C.

Let's think about the function that return 0 if false, otherwise 1.

 => Naive way : return (e)? 1: 0;

C doesn't support boolean type. Instead, 0 is false, non 0 is true in C.
There is no fixed value to represent TRUE.
But, as defined by 4.5/4, boolean true is promoted to 1, boolean false to 0.
So, we can improve this to

 => Better way : return !!(e);

And this way is also useful because we can get fixed integer value - integer 1 - for TRUE boolean value.

The only requirement is "Those should be fully evaluated before function is called."

Trackback 0 : Comment 0