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;
}
commented: excellent answed my question first post +1

Thank you ancient dragon, you have solved my problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.