Call-by-reference and Call-by-value

914 views Asked by At

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.

1

There are 1 answers

8
Nard On BEST ANSWER

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 from value in main, just that it has the same value. However, int &value is a reference to value in main, which means it is safe to think of it as the value in main itself.

If you print value in triple_by_value after value *= 3 you will get the value that you want. If you want value in main to have the new value, you can assign the new value to value in main by doing value = triple_by_value(value); in main, or simply use triple_by_reference.