I had a controversy about what compilers \"think\" about this:
a = 8;
b = !!a;
So, is b == 0x01 ? Is TRUE always
The result of the logical negation operator
!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint. The expression!Eis equivalent to(0==E). C11 §6.5.3.3 5
b below will typical have the value of 1 (or possible -1, see below).
a = 8;
b = !!a;
So, is
b == 0x01?
Yes (* see below)
Is
TRUEalways0x01or it may be0xFF,0xFFFF,0xFFFFFFFFetc..?
In , true is a macro with the integer constant 1. TRUE is not defined by the C standard. Various implementations defines it with the value of 1. It might be have other values. It certainly should be non-zero.
what is better to use?
A) a>0?1:0
B) !!a
Both result in an int with the value of 0 or 1. A reasonable to good compiler would be expected to generate the same code for both (if a in not signed). Use the form that 1) adhere to your groups coding standard or else 2) best conveys the meaning of code at that point. A third option which results in type (bool):
C) (bool) a
If a is signed , then a>0?1:0 is not equivalent to !!a. a != 0 ? 1 :0 is equivalent of !!a.
* If b is a 1 bit signed bit field, b = !!8 will have the value of -1.