I am writing a program that lets the user input an integer into the variable value
, and calls the two alternate functions, each of which triples the chosen integer value.
The function triple_by_value
passes the variable number by value, triples the parameter and returns the result.
The function triple_by_reference
passes the variable number by reference, and triples the original value of number through the reference parameter.
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a number (-1 to end): ";
cin >> value;
if (value != -1)
{
triple_by_value(value);
cout << "Triple-By-Value: " << value << endl;
triple_by_reference(value);
cout << "Triple-By-Reference: " << value << endl;
}
return 0;
}
int triple_by_value(int value)
{
value *= 3;
return value;
}
int triple_by_reference(int &value)
{
value *= 3;
return value;
}
It seems I'm having a problem where the function triple_by_value
isn't, well, tripling the value, just printing it as is.
Any help would be much appreciated.
As the name suggests, passing a variable by value means that the function only gets the value of the variable and not access to the variable itself.
In your example,
int value
is a whole different variable fromvalue
inmain
, just that it has the same value. However,int &value
is a reference tovalue
inmain
, which means it is safe to think of it as thevalue
inmain
itself.If you print
value
intriple_by_value
aftervalue *= 3
you will get the value that you want. If you wantvalue
inmain
to have the new value, you can assign the new value tovalue
inmain
by doingvalue = triple_by_value(value);
inmain
, or simply usetriple_by_reference
.