user768417
user768417

Reputation:

Struct Giving Incorrect Output

When I compile this code, I get an output of 10 when it should be 0.

#include <iostream>

struct player
{
    int hp;
    int dmg;
};

void dealdamage(player x, player y)
{
    y.hp = y.hp - x.dmg;
}

int main()
{
player p1, p2;
p1.hp = 10, p1.dmg = 10;
p2.hp = 10, p2.dmg = 10;
dealdamage(p1, p2);
std::cout << p2.hp << std::endl;
return 0;
}

Can anyone explain why?

Upvotes: 1

Views: 92

Answers (1)

Mysticial
Mysticial

Reputation: 471229

That's because you're passing the player structs in by value.

When the parameter is passed by value, a copy is made into the called function. So whatever changes you make in the function won't affect the original.

So your statement:

y.hp = y.hp - x.dmg;

Only affects the local copy of x and y. Which falls out of scope and is thrown away after the function ends.

The solution is to pass by reference like this:

void dealdamage(player &x, player &y){

In this case, then changes made to x and y will be affect the originals.

Upvotes: 3

Related Questions