Is there a better way of writing v = (v == 0 ? 1 : 0); [closed]
You can simply use:
v = 1 - v;
This of course assumes that the variable is initialised properly, i.e. that it only has the value 0 or 1.
Another method that is shorter but uses a less common operator:
v ^= 1;
Edit:
To be clear; I never approached this question as code golf, just to find a short way of doing the task without using any obscuring tricks like side effects of operators.
Since 0
is a false
value and 1
is a true
value.
v = (v ? 0 : 1);
If you are happy to use true
and false
instead of numbers
v = !v;
or if they must be numbers:
v = +!v; /* Boolean invert v then cast back to a Number */
v = (v + 1) % 2
and if you need to cycle through more values just change 2
for (n + 1)
. Say you need to cycle 0,1,2 just do v = (v + 1) % 3
.