Toggling -1 and 0 using single line of code

Hey everyone,

I'm a beginner in programming and I want to know how you can toggle -1 and 0 using just a single line of code. I know you can do it with 'If' statements but how do you do it with just a single line of code?

Thank you very much :)
Assuming you're using an integer (not a floating point), and assuming -1 and 0 are the only possible values, you can use XOR. XOR can toggle between any two values if you know how to use it. For -1 and 0:

 
val ^= -1;


You can also slip in NOT, with a negative:

 
val = -(!val);


Or you can fall back to the ternary operator (basically 'if' with different syntax):

 
val = (val == 0) ? -1 : 0;
Another way:

val = -( 1 + val );

val=~val;

By the way, is there any platform out there that doesn't use two's complement?
Last edited on
Yes, quite a few, but they are increasingly uncommon.
Topic archived. No new replies allowed.