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 valueis a whole different variable fromvalueinmain, just that it has the same value. However,int &valueis a reference tovalueinmain, which means it is safe to think of it as thevalueinmainitself.If you print
valueintriple_by_valueaftervalue *= 3you will get the value that you want. If you wantvalueinmainto have the new value, you can assign the new value tovalueinmainby doingvalue = triple_by_value(value);inmain, or simply usetriple_by_reference.