Why isn't this working?

MainGame.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include "functions.h"
using namespace std;

int main()
{
	int attack;
	Leviathan(attack);
	cout << "Attack: " <<attack << endl;
	system("pause");
	return 0;
}


functions.h
int Leviathan(int attack);

MonsterList.cpp
1
2
3
4
5
int Leviathan(int attack)
{
	attack = 5;
	return attack;
}


I'm trying to get attack to return from MosterList.cpp to MainGame.cpp as 5.
But it is always 0.

How do I get it to return what I changed in the MonsterList.cpp?
Last edited on
The function takes attack by value, meaning that it creates it's own attack inside the function. In order to change the value of main's attack, you need to pass it by reference by using the & symbol:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//note void return
void byReference(int& i)
{
  i++;
}

int byValue(int i)
{
  i += 10;
  return i;
}

int main(void)
{
  int myInt = 0;
  byReference(myInt);
  int anotherInt = byValue(myInt);

  cout << "myInt: " << myInt << "Another int: " << anotherInt << endl;
  return 0;
}

Last edited on
Thank you so much!! Works perfect now!!
Topic archived. No new replies allowed.