Hello all im trying to work out whats wrong with this code,

#include <iostream>

using namespace std;

int player1score = 0; // global variable


int add10 (int &score) // function that adds 10 to player1score variable by reference
{
	return(score + 10);
}

int main ()
{
	cout << "Please enter player score " << endl; 
	cin >> player1score; 
	add10 (player1score); // calls the function by reference
cout << "the number you entered with the function added is " << player1score;
}

That code does not work but when passing arguments by value that code does work

#include <iostream>

using namespace std;

int player1score = 0; // global variable


int add10 (int score) // function that adds 10 to player1score 
{
	return(score + 10);
}

int main ()
{
	cout << "Please enter player score " << endl; 
	cin >> player1score; 
	player1score = add10 (player1score); // calls the function 
	cout << "the number you entered with the function added is " << player1score;
}

im very confused please help

>>player1score = add10 (player1score);

The first example doesn't work because it never changes the value of player1score variable. In the above code, when add10() returns it assigns the return value to player1score. That is not done in the first example. Passing a variable by reference does not do anything if the function does not change its value. Modify the first example like this and you will see the difference

int add10 (int &score) // function that adds 10 to player1score variable by reference
{
      score += 10;
      return score;
}

Edited 6 Years Ago by Ancient Dragon: n/a

Comments
excellent answed my question first post
This question has already been answered. Start a new discussion instead.