Changing variables from functions

I am making a simple text-based rpg game. I made a lot of it before i knew about functions, so now i am organizing it into some. I put the weapon shop into its own function:

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
void weaponShop(int gold, int attackPower)
{
	int choice;
	cout << "\n-----------------------------------\n";
	cout << "\nYour Gold: " << gold << endl << endl;
	cout << "(1)Stick: 5G\n";
	cout << "(2)Wooden Sword: 20G\n";
	cout << "(3)Iron Sword: 50G\n";
	cout << "(4)Back\n";
	cin >> choice;

	if (choice == 1 && gold >= 5 && attackPower < 6)
	{
		cout << "\nYou bought a Stick!\n\n";
		gold -= 5;
		attackPower = 6;
	}
	else if (choice == 2 && gold >= 20 && attackPower < 10)
	{
		cout << "\nYou bought a Wooden Sword!\n\n";
		gold -= 20;
		attackPower = 10;
	}
	else if (choice == 3 && gold >= 50 && attackPower < 20)
	{
		cout << "\nYou bought an Iron Sword!\n\n";
		gold -= 50;
		attackPower = 20;
	}
	else if (choice == 4)
	{
		cout << "\nYou walk back outside.\n\n";
	}
	else if (choice > 4 || choice < 1)
	{
		cout << "\nInvalid character!\n\n";
	}
	else
	{
		cout << "\nInsufficient funds!\n\n";
	}
}


When I want to open use it, I use

 
weaponShop(gold, attackPower);


(gold and attackPower are variables in int main().)

The issue is that gold and attackPower only changed in the function, not in int main. So if you buy something, your gold doesn't go down, and your attackPower doesn't go up.

I don't think i can use something like
 
gold -= weaponShop(gold, attackPower);

and give weaponShop a return value of the gold used, because then then attackPower wont change.

I know I could use global variables, but I'm not sure if that is the best solution, because they are said to make the code messy.

Also, if i am doing something horribly wrong and/or inefficient, please say so.
Last edited on
The issue is that gold and attackPower only changed in the function, not in int main.
There are two ways to pass arguments (the parameters) to a function. You can pass them by value or pass by reference.

When you pass by value, changes made in the function are not reflected in the calling function, main() in this case. This what you are currently using.

When you pass by reference, changes made in the function are reflected in the calling function.

The syntax for call by reference is:
 
void weaponShop(int& gold, int& attackPower)
Last edited on
Cool, that works, thanks for the reply!
Topic archived. No new replies allowed.