How to toggle an int / _Bool in C
boolean, c, int, toggle
Solution
`value = !value;` expresses what you want to do directly, and it does exactly what you want to do by definition.
Use that expression.
From C99 6.5.3.3/5 "Unary arithmetic operators":
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 type int. The expression !E is equivalent to (0==E).
Problem
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` is `1`? - 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` (or `bool` 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.