In C a value of 0 is considered "false", and any other (nonzero) value is considered "true". So one, very explicit way to convert an arbitrary int
value to an explicitly true-or-false Boolean value is to use the (C99 and later) bool
type:
#include <stdbool.h>
int i;
bool b;
b = (i != 0) ? true : false;
But since the !=
operator essentially "returns" a Boolean value, you can also do
b = (i != 0);
And since the zero/nonzero definition is built in to the language, you can also just do
b = i;
But you don't have to use type bool
. If you have an arbitrary-value int and you want to force it to 0/1 "in place", you have the same sorts of options:
i = (i != 0) ? 1 : 0;
Or
i = (i != 0);
Or there's another common trick:
i = !!i;
This last is concise, popular, and somewhat obscure. It changes zero/nonzero to 1/0 and then back to 0/1.
I've shown these examples using type int
, but they would all work just as well with short int
or char
(i.e. byte).
One more thing. In your question you wrote val = (val == 1) ? 0 : 1
, but that's basically meaningless. In C, at least, everything (everything!) follows from whether a value is zero or nonzero. Explicit comparisons with 1 are almost always a bad idea, if not a downright error.