Quick Toggle question
Is there a quick one line way to toggle a value? i.e. instead of...
1 2 3 4 5
|
if(togglevalue)
togglevalue = 0;
else
togglevalue = 1;
|
Thanks!
If you are only interested in two states then you can use the
bool data type, which is either
true or
false
1 2
|
bool toggle = false;
toggle = !toggle; //toggle now is true
|
Last edited on
togglevalue=(togglevalue==1)?0:1;
bool > int for this purpose...go with Faldrax's solution. If you MUST go with an int, you can do what Nandor said.
huh, I've never seen notation as in Nandor's reply (specifically a colon and a question mark). Can you explain what that means?
Thanks btw.
It is the ternary operator.
The algorithm
1 2 3 4
|
if( condition )
variable = value1;
else
variable = value2;
|
can be rewritten as a one-liner:
|
variable = condition ? value1 : value2;
|
However to shorten up Nandor's example even more:
|
togglevalue = 1 - togglevalue;
|
assuming togglevalue is either 0 or 1 to start with.
The ternary operator works as follows:
x ? y : z
if x is true it returns y, if not it returns z.
cool beans!
Topic archived. No new replies allowed.