Monday, October 29, 2012

One of the few cases where I'll use the ternary operator.

The ternary operator in C/C++ is of the form "? : " and is mainly used to cram an if-statement into one line and write unreadable code :)

I generally steer clear of it but there is one type of situation where I'm willing to use it. Printing out the state of a boolean in a printf statement. C didn't have a boolean type, printf is from C, so there's no support in printf for boolean types. But booleans are an everyday type now and you'll often find yourself wanting to print out the state of a bool.

You can't do this:

printf("isSoundOn = %b", isSoundOn);

There's no escape character for bools but you can use the ternary operator.

printf("isSoundOn = %s", isSoundOn? "true" : "false");

That will do the trick. I think it's reasonably straight forward and actually doing a full if statement across multiple lines would make things harder to read for such a simple action. I did see an interesting alternative on Stackoverflow with no branch, from memory it was this:

&"false\0true"+6*isSoundOn

That probably needs some braces and maybe some casts to compile but basically it's moving the pointer to the start of the "true" substring if isSoundOn is true. If isSoundOn is true it will have a value of 1 otherwise 0, 6 is the length of false including the termination character. So 6 * 1 moves the pointer to "true", 6 * 0 keeps the pointer at the start of the string and printing will end when it reaches the terminating character \0. Clever but too magical for regular code I think.

No comments: