Suppose we have an int
and want to toggle it between 0
and 1
in a boolean fashion. I thought of the following possibilities:
int value = 0; // May as well be 1
value = value == 0 ? 1 : 0;
value = (value + 1) % 2;
value = !value; // I was curious if that would do...
- The third one seems to work. Why? Who decides that
!0
is1
? - Is something wrong with any of these?
- Are there other possibilities? e.g. bitwise operators?
- Which offers the best performance?
- Would all that be identical with
_Bool
(orbool
from stdbool.h)? If not, what are the differences?
EDIT: Many great answers with lots of valuable information, thanks! Unfortunately, I can only accept one.