Ask coding questions

← Back to all posts
How do I change a variable for a function in a different function in C++?
LoveFromSkyy (137)

I want the player's XP to go up by 100 when they beat the level (When the monster's health reaches 0 or below). How do I do that?

Answered by Coder100 (18930) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (18930)

the easiest way is to have a global var this way both functions can access it

int xp;

void fight() {
  xp++;
}

int main() {
  // you have xp health
}
LoveFromSkyy (137)

What does
xp++;

do?
Also, to make a global variable, I don't declare it inside of a function?
@Coder100

Highwayman (1505)

I think the problem is just a little bit deeper here. Let me ask you a question: Should the level really be creating the player, or should it just be affecting the player? It should be affecting the player! The problem here is that you are creating the character inside of the level, instead of inside of the game. So ultimately, your program should look more like

Hero playLevel(Hero player)
{
  // use player...
  player.xp += 100;
  return player;
}

void playGame()
{
    struct Hero player;
    // init player...
    playLevel(player);
}
Andy_4sberg (54)

I don't really know C/C++/C#, but hope this helps!

if (VARIABLE_STORING_MONSTER_HEALTH<1) {
    VARIABLE_STORING_XP += 100;
}