I was reading JS manual, and found nice trick, that ~val === (val != -1).
I found it nice, and want to use it in my C code.
Is it portable? I checked on my GNU/Linux box, it work.
EDIT: Seems I asked not too clearly. Of course, I know, there is no === in C.
Question is, are both conditionals
int val;
if (~val) {...}
if (val != -1) {...}
equal?
The following answer was written for the question as it was originally phrased, which led myself and others to think that he was asking whether
~ansand(ans ^ -1)are equivalent.This trick is not as portable as
~valbecause it assumes that-1 == 0b111111111..., which is true only on a two’s complement machine (granted, that holds for virtually any machine today). It exploits the fact that the xor operation works as a “controlled inverter”, flipping each bit in its left operand for which the corresponding right operand bit is one.However, substituting
~0for-1might work.