int exp_adder( int exp )
{
if ( win )
{
experience += 20;
if( experience == 100 ) //experience and character_level is global
{
character_level++;
if ( true )
{
experience = 0;
}
}
}
return experience,character_level;
}
would this function work?
i mean, i did not use exp which i declared in the parameter of this function.
i did call this function to main but it works, the exp became 20 from 0.
it returns what it should be.
This will always be executed because if(true) will always evaluate to true.
Also you can only be returning 1 thing, I'm not even sure how that compiles but it definitely isn't doing what you think it is. (Edit: Oh right, see keskiverto's answer, but yeah it still isn't doing what you want it to)
Why not use classes?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//Player class defintion stuff left out
//members:
private:
int exp;
int level;
...
void Player::addExp(int amount)
{
exp += amount;
if (exp >= 100)
{
level++;
exp = 0; //or exp = 100 - amount; although this doesn't take into amount being over 100.
}
}
As pointed out, globals aren't normally a good idea (I only do globals if I make them constants; ie. constint SCREEN_W = 640;). If you are needing to return more than one variable you should pass by reference so that the function can modify the values in the function (shown below). As Ganado pointed out, you could use a class.
#include <iostream>
// this is just an example for my reference comment
void exp_adder(int &exp, int &char_lvl, char win)
{
if(win == 'w'){
exp += 20;
if(exp == 100){
char_lvl++;
exp = 0;
}
}
// no penalties for losing right now so no need for else
}
int main()
{
int experience = 0, level = 1;
char winLose = ' ';
do{
std::cout << "Did you win or lose the battle? ([w]in [l]ose [q]uit): ";
std::cin >> winLose;
exp_adder(experience, level, winLose);
std::cout << "\n\nCharacter Level: " << level
<< "\nExperienc points: " << experience << std::endl;
}while(winLose != 'q');
return 0;
}
Did you win or lose the battle? ([w]in [l]ose [q]uit): w
Character Level: 1
Experienc points: 20
Did you win or lose the battle? ([w]in [l]ose [q]uit): l
Character Level: 1
Experienc points: 20
Did you win or lose the battle? ([w]in [l]ose [q]uit): l
Character Level: 1
Experienc points: 20
Did you win or lose the battle? ([w]in [l]ose [q]uit): w
Character Level: 1
Experienc points: 40
Did you win or lose the battle? ([w]in [l]ose [q]uit): l
Character Level: 1
Experienc points: 40
Did you win or lose the battle? ([w]in [l]ose [q]uit): q
Character Level: 1
Experienc points: 40