Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

nickculbertson

macrumors regular
Original poster
Nov 19, 2010
226
0
Nashville, TN
Hello,
I think this should be an easy question for most but I'm having trouble finding the answer. I know how to switch between cases using rand and arcrand but how do I switch them in order 1,2,1,2,1,2,1,2...

Code:
// for random
int Number = rand() % 2;
switch (Number){
		case 0:{
                         NSLog(@"one");}
			break;
		case 1:{
			NSLog(@"two");}
			break;
		default:
			break;
	}	
	
}

// for non random

int Number = //How do I just make this = 2
switch (Number){
		case 0:{
                         NSLog(@"one");}
			break;
		case 1:{
			NSLog(@"two");}
			break;
		default:
			break;
	}	
	
}

thanks,
Nick
 
Last edited:
XOR it:


Code:
int Number = 1;
Number = Number ^ 1; // i is now 0
Number = Number ^ 1; // i is now 1
Number = Number ^ 1; // i is now 0
 
XOR it:


Code:
int Number = 1;
Number = Number ^ 1; // i is now 0
Number = Number ^ 1; // i is now 1
Number = Number ^ 1; // i is now 0

This sounds a lot better than my solution, but I'll post mine anyway, just in case someone wants to have a higher sequence, for example 0,1,2. And of course number_ is an iVar or global variable, something that is going to stick around.

Code:
#define SEQUENCE_COUNT 3
number_++;
switch(number_ % SEQUENCE_COUNT) {
    case 0:
        // Do some stuff
        break;
    case 1:
        // Do some stuff
        break;
    case 2:
        // Do some stuff
        break;
    default:
       // Shouldn't ever get here!
       break;
}
 
In this case, NOT would be just fine, no?

Code:
int number = 0;
number = !number; //1
number = !number; //0
number = !number; //1

I know many of you don't like seeing seemingly boolean operators as integers...

(EDIT: I was going to add something about mod, but seepel got to it first.)

B
 
In this case, NOT would be just fine, no?

I think using ! is probably better.

You can look at that and know exactly what it's doing quickly, versus using XOR and having to think about your bitwise math. The modulo operation is definitely good too for the reasons mentioned (ability to two more than just 2 numbers).
 
And for completeness, if you need to oscillate between two values that don't happen to be 0 and 1 you can do it like this

Code:
#define kValue1 27 // or whatever
#define kValue2 42  // or whatever

// Setup
int currentValue = kValue1;

// Oscillate
currentValue = (kValue1 + kValue2) - currentValue;

Obviously that code also works with values of 0 and 1 but using a boolean and currentValue = ! currentValue is more idiomatic for that case.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.