Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What double negation does in C

Tags:

c

I had a controversy about what compilers "think" about this:

a = 8;
b = !!a;

So, is b == 0x01 ? Is TRUE always 0x01 or it may be 0xFF, 0xFFFF, 0xFFFFFFFF etc..?

If I want to extract only 0x00 if (a == 0) and 0x01 if (a > 0) does this double negation approach works?

In other words: to obtain result only 0 or 1, what is better to use?

a) a>0?1:0; b) !!a

I hope you understand my question.

like image 928
Hairi Avatar asked Oct 30 '25 01:10

Hairi


2 Answers

Yes, b == 1. The result of any boolean operator is always 0 or 1. You can do better though...

I want to extract only 0x00 if (a == 0) and 0x01 if (a > 0)

b = a > 0; most accurately reflect your rule.

like image 161
QuestionC Avatar answered Oct 31 '25 15:10

QuestionC


You have not supplied enough information to tell whether !!a works for your purposes or not.

You stated that you really need the result of a > 0. However, this is not equivalent to !!a if a is signed and holds a negative value. If this is possible, then the answer is obviously "no".

!!a is equivalent to a != 0, not to a > 0.

like image 20
AnT Avatar answered Oct 31 '25 13:10

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!