Pass byreference

I'm trying to learn pass byreference. I was wondering if someone could explain how to do this properly.

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
#include <iostream>
#include<string>
using namespace std;

void DealDamage(int &EnemyHealth, int DamageAmount, string EnemyName)

int main()
{

    int EnemyHealth, DamageAmount;
    DamageAmount = 50;
    EnemyHealth = 100;
    string EnemyName = "a rat";

    cout << "Health before function call: " << EnemyHealth;

    DealDamage(EnemyHealth, DamageAmount, EnemyName);

    cout << "Health after function call: " << EnemyHealth << endl;

    return 0;
}

void DealDamage(int &EnemyHealth, int DamageAmount, string EnemyName)
{
    &EnemyHealth-=DamageAmount;
    cout << "blade does " << DamageAmount << " damage to " << EnemyName << endl;
}


error: expected initializer before 'int'
In function 'void DealDamage(int&, int, std::string)':|
lvalue required as left operand of assignment|
||=== Build finished: 2 errors, 0 warnings ===|
Last edited on
Try "int& enemyHealth" instead of "int &EnemyHealth". That should do it for you! Good luck!
Get rid of the & here:

&EnemyHealth-=DamageAmount;

When you pass by reference using a C++ Reference (notice the capitalization) as in your code, you don't need to add any extra syntax when you refer to the variable within the function. Its value gets automatically updated in the caller.

Also note that the variable isn't &EnemyHealth of type int, it's EnemyHealth of type int&.
Last edited on
Thanks guys. One more error.

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
#include <iostream>
#include<string>
using namespace std;

void DealDamage(int &EnemyHealth, int DamageAmount, string EnemyName)

int main()
{

    int EnemyHealth, DamageAmount;
    DamageAmount = 50;
    EnemyHealth = 100;
    string EnemyName = "a rat";

    cout << "Health before function call: " << EnemyHealth;

    DealDamage(EnemyHealth, DamageAmount, EnemyName);

    cout << "Health after function call: " << EnemyHealth << endl;

    return 0;
}

void DealDamage(int& EnemyHealth, int DamageAmount, string EnemyName)
{
    EnemyHealth-=DamageAmount;
    cout << "blade does " << DamageAmount << " damage to " << EnemyName << endl;
}


line seven error: expected initializer before 'int'|


the errors showing up on int main()
Last edited on
You're missing a semi-colon after the function prototype.
oh, lol, simple enough. stupid mistake, thanks for pointing this out.

I prefer this method over passing in pointers. Makes everyone's life a little easier, lol.
Topic archived. No new replies allowed.