Loop main() without redeclaring variables?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;
class Player{

public:
       int XP;
       int MXP;
       int Lvl;
       void Levelup();
       void AddXP(int howm);
       int GetLvl();
       int Declare();

};     
void Player::Levelup(){
     if(XP >= MXP){
           Lvl += 1;
           XP = 0;
           MXP += 10;
     }
}
void Player::AddXP(int howm){
     XP += howm;
     Levelup();
}
int Player::GetLvl(){
     return Lvl;
}
int Player::Declare(){
     XP = 0;
     MXP = 10;
     Lvl = 1;
}

int main(void){
    int add;
    Player Player;
    Player.Declare();
    cout << "You are level ";
    cout << Player.GetLvl();
    cout << ". How much XP do you want to add?\n";
    cin >> add;
    Player.AddXP(add);
    main();
}

           
     



Hi! New to the forums. I'm also new to C++.

I was exploring console application capabilities. Since I plan to be a video game programmer, I decided to experiment with "Level up" features.

When I ran this code, the Level variable remained the same. I found out that it was because it kept on running the Declare() void, giving it no chance to tell me the new level. Is there a workaround for this?
Don't ever directly call the main function like that, it will cause problems.

You could just put the code that you want to keep repeating inside it's own loop like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

int main(void){
    int add;
    Player Player;
    Player.Declare();

    while(true)
    {
	cout << "You are level ";
	cout << Player.GetLvl();
	cout << ". How much XP do you want to add?\n";
	cin >> add;
	Player.AddXP(add);
    }
}


(You can put some sort of condition for it if you want to break out of it at some point).
Also Declare() isn't returning anything so it shouldn't have an int return type.
Last edited on
Thank you!
According to section 3.6.1 Main function of the C++ Standard

3 The function main shall not be used within a program


However in C the main may be used within a program.
Topic archived. No new replies allowed.