tags:

views:

311

answers:

5

What is the most elegant way to do the next stuff:

int i = oneOrZero;

if (i == 0) {
   i = 1;
} else {
   i = 0;
}

You can assume that i can have only 1 or 0 value.

+25  A: 

subtraction?

i = 1 - i;
Jimmy
nice. I thought about binary operations and didn't look to more simple solutions.
Roman
Wait... that comes from a mathematician ;)
AraK
The real question is, would you add a comment saying "flip the value of i" or just leave it alone?
Yar
@yar: I personally find XOR more meaningful in a "flip value" sense, so I'd probably comment a subtraction. However, some people get inexplicably anxious whenever they see a bitwise operator, so you might have to comment either way.
Jimmy
+29  A: 

i ^= 1;

XOR the value with 1. This gives you both ways (in case you need to flip 0 <--> 1 either way):

0 ^ 1 = 1
1 ^ 1 = 0
Yuval A
This is not only shorter, but to me carries the meaning a little better than the subtraction answer.
gWiz
+1  A: 

i = (i == 0)?1:0 is one way, though I like @Jimmy's and @Yuval's versions better.

Chinmay Kanchi
I prefer this one as when I read the code I know exactly what its supposed to be doing. The subtraction is too clever for that, XOR is not common of an operation that I'm going to recognize it immediately.
Frank Schwieterman
@Frank Schwieterman: In my experience, the ? operator isn't that common either. If you've never seen the ? operator, it's not obvious what's happening. I'd go with the XOR (and maybe comment it).
GreenMatt
Hmm good point. From my perspective I'm going to recognize ? before ^, but I suppose thats not universal.
Frank Schwieterman
@GreenMatt: I agree the both are uncommon. Rather than any personal preference or perception of overarching commonality, I'd decide based on the rest of the code base - that is, if the ternary operator is common elsewhere in code that the future developer sees, pick it; if bit-wise operations are common, go with that. If there's no way to decide based on that criteria, performance test (which I'd guess favors XOR, but who knows).@Chinmay: why not test on oneOrZero, and assign only once?
Carl
@Carl: What do you mean?
Chinmay Kanchi
make it right in the declaration: int i = (oneOrZero==0)?1:0; - i suppose that assumes that there's no intervening computation that uses the value of i, which may not be accurate.
Carl
Ah, I read the OP's code as `int i = 1` OR `int i = 0` rather than a variable called oneOrZero...
Chinmay Kanchi
+3  A: 

Use bit xor

i ^= 1;

doc
+2  A: 

i = ( i + 1 ) % 2, though I think we all agree the subtraction or xor method is better! (Though it has the added benefit of "flipping the switch" for more than binary.)

Larry