

Beautiful Code: Is there a better way of writing v = (v == 0? 1 : 0); - hydrazine
http://stackoverflow.com/questions/6911235/is-there-a-better-way-of-writing-v-v-0-1-0

======
Cushman
Summary: No.

Long version: There are a number of ways which are lexically shorter, do the
same thing only assuming that v is already either 0 or 1, are not self-
documenting, and perform worse or marginally better at best. Only a very
tortured definition would call any of these things "better".

Although v = v ? 0 : 1 isn't that bad.

~~~
ldite
Actually the "v = (v + 1) % 2" approach has merit -- in the past I've had to
write MHEG textual notation, which is a declarative language where the syntax
for conditionals is phenomenally ugly and ludicrously verbose, and this method
is vastly more concise (2 lines versus about 10)

------
gte910h
If you insist on one line

    
    
        if (v>0) v=0; else v=1;
    

Otherwise

    
    
        if(v>0)
          v=0;
        else
          v=1;
    

Some of us prize readability over neat tricks. I think there are a 100 ways
most of these answers could be misinterpreted by people. Code is read more
than it is written, and programs rarely work better because you wrote it
slightly more "impressively". Modern compilers do much of this sort of stuff
that they are doing in this thread, but they do it in a repeatable manner
which future programmers don't have to puzzle out.

------
codeslush
v = !v - if toggling between true | false

------
michaelcampbell
Are you just toggling between 1 and 0?

Why not v = 1 - v?

------
wycats
v ^= 1 in Ruby should work.

------
DrJ
v = v || 1;

