Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle an int / _Bool in C

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...
  1. The third one seems to work. Why? Who decides that !0 is 1?
  2. Is something wrong with any of these?
  3. Are there other possibilities? e.g. bitwise operators?
  4. Which offers the best performance?
  5. 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.

like image 334
riha Avatar asked Oct 31 '12 08:10

riha


1 Answers

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).

like image 61
Michael Burr Avatar answered Nov 12 '22 03:11

Michael Burr