0

I am trying to modify a program so that it used 2 variables rather than one. I have tried to get help through the other discussions on this topic but they are all talking about passing by reference not value.
My code is:

#include < iostream >
using std::cout;
using std::endl;

int incr10(int num);    // Function prototype

int main(void)
{
    int num(3);
    cout < < endl < < "incr10(num) = " < < incr10(num) < < endl
     < < "num = " < < num < < endl;
    return 0;
}
    // Function to increment a variable by 10
    int incr10(int num)    // Using the same name might help...
{
    num += 10;      // Increment the caller argument – hopefully
    return num;     // Return the incremented value
}
3
Contributors
2
Replies
23
Views
3 Years
Discussion Span
Last Post by ann.mughal.5
0

If I understand your question correctly, you want to modify the program to pass two values to the function, both to be modified, and get the two new values back in main?

For that to happen, you're going to have to pass at least one of the two arguments by reference. You could in that case return one modified value and "pass back" the other though its reference argument. But that's not an ideal method.

I would pass both value by reference and get the results back that way.

int main( )
{
    int n1 = 5;
    int n2 = -10;

    cout << "Numbers before function call: " << n1 << "  " << n2;

    incr2( n1, n2 );

    cout << "Numbers after function call: " << n1 << "  " << n2;

    return 0;

}




void incr2(int & num1, int  & num2)    
{
    num1 += 10;     
    num2 += 10;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.