Anthony
Anthony

Reputation: 259

XCode - Redefine macro

Small problem I'm having where I have an amount of objects (enemies) on the screen at one particular time and cannot redefine their value. I set my enemies to begin with 3 on the screen.

My objective is to change the amount of enemies based on the current score.

I've attached snippets of the code below.

#define kEnemies 3

- (void) EnemyIncrease 
{
    if (self.score>=100) {
    #define kEnemies 4
    }
}

// I've also tried amongst other things

#define kEnemies 3

- (void) EnemyIncrease
{
  if (self.score >=100) {
    #undef kEnemies
    #define kEnemies 6
  }
}

Would really appreciate some assistance.


I have now changed my code to the following

int numberOfEnemies;

if (self.score>=0) {
 numberOfEnemies = 3
}

else if (self.score>=100) {
 numberOfEnemies = 4
}

however the issue now is that the array does not update the numberOfEnemies when the score meets the new condition.

for(int i = 0; i < numberOfEnemies; i++)

Apologies I'm still new to coding and trying to modify existing code

Upvotes: 2

Views: 3719

Answers (1)

James Webster
James Webster

Reputation: 32066

Macros are preprocessed, that means that they are processed before the rest of your code is even compiled.

Taking out your code, that means the preprocessor sees this (using your second example). Ultimately, the value of kEnemies is 6:

#define kEnemies 3
#undef kEnemies
#define kEnemies 6

It's not really viable to use #defines for variables, I only use them for constants.

You could use a member variable:

int numberOfEnemies;

...

if (self.score >=100) 
{
    numberOfEnemies = 6
}

(I removed the k prefix as this style is intended for constants)

Upvotes: 6

Related Questions