On Fri, 2010-12-03 at 11:32 +0100, Christian Corti wrote:
On Fri, 3 Dec 2010, Kevin Schoedel wrote:
Also,
"TF"[!b]
This is a great example!
Now let's guess why this works, but not "FT"[b]
The compiler returns either 0 or 1 for the unary inversion operator. The
C standard dictates that 0 is false, anything else is true. Problem is,
'b' can contain damn near anything and still be true.
So "FT"[b] with b=0x80 -- b is still true, but you get an access
violation, or possibly just a crap result. If your boolean is a true
boolean (i.e. only 0 and 1 are valid values, for false and true
respectively) then the code *will* work.
So you use the unary negation operator, which turns your 0x80 (true)
into 0 (false). "TF"[0] is "T", because the original value was true.
Similarly, !0 = 1, and "TF"[1] is "F".
However: the compiler would still be correct to use the value 123
instead of 1, thus that code may not work... So it's compiler dependent,
but most compilers use 0/1 for boolean results, meaning you might not
spot the Big Nasty Bug until much, much later.
A better way:
b?'T':'F'
If b is true, then this statement evaluates to 'T', otherwise it
evaluates to 'F'. Just it does it without tricky pointer math, and is
more likely to work across different compilers.
--
Phil.
classiccmp at philpem.me.uk
http://www.philpem.me.uk/