If you ever come upon a need to toggle an integer value between 1 and 0, consider using the bitwise exclusive-OR (^) operator in C to get the job done.
In a recent application I wrote a method with one parameter, an integer, that is expected to be 1 or 0. In creating a demo of the application I wanted to pass in alternating values of 1 and 0 as part of a test for a specific use case. Instead of using an if statement in the calling method to decide when to send a 1 or 0, I wrote something similar to the code below:
- (void)someMethod
{
static int x = 0;
// Toggles 1 to 0 and 0 to 1 using xor
x ^= 1;
// Call the method that expects a 1 or 0
[methodCallHere toggle:x];
}
More often than not, exclusive-OR (^), AND (&) and inclusive-OR (|) are consider a bit-level operations (see this post on bitfields). However, there are times when these operators work equally well with integer values.
Comments
5 Responses to “Toggle an Integer Between 1 and 0”
Leave Comment
All Content Copyright © 2008-2012 • iOS Developer Tips, All Rights Reserved.
Pretty handy to use this with the bitfields from a previous post of yours.
typedef struct {
unsigned preLoaded;
unsigned saveState;
unsigned saveLoginName;
} SomeStatus;
SomeStatus status;
status.preLoaded = 1;
status.saveState = 0;
status.saveLoginName = 1;
status.preLoaded ^= 1;
if( status.preLoaded == 0 )
NSLog(@”preloaded is off”);
else
NSLog(@”preloaded is on”);
if( status.saveState == 0 )
NSLog(@”saveState is off”);
else
NSLog(@”saveState is on”);
if( status.saveLoginName == 0 )
NSLog(@”saveLoginName is off”);
else
NSLog(@”saveLoginName is on”);
[Reply]
Same as using a bool and doing..
BOOL someBool = NO;
someBool = !someBool;
//someBool is now YES
[Reply]
Another way is this:
x = 1 – x;
If x is 1, it is now 0. If it was 0, it’s now 1. Pretty much the same thing as using XOR, but much simpler to understand.
[Reply]
If you’re using the int as a kind of flag…
You might remember your end of last year: http://iphonedevelopertips.com/objective-c/of-bool-and-yes.html
BOOL is nothing else than a signed char, and YES is defined as 1 (NO is 0), you can even write:
static int x = 0;
// Toggles 1 to 0 and 0 to 1 using !
x = ! x;
[Reply]
bitwise operations like ^ tend to be significantly faster than other operations.
[Reply]