For example, if I have a function using all local variables:
1 2 3 4 5 6 7 8 9
void functionone( void ){
int firstnumber;
int secondnumber;
int thirdnumber;
int sum = 0;
cout << "Enter three separate numbers: ";
cin >> firstnumber >> secondnumber >> thirdnumber;
sum = firstnumber + secondnumber + thirdnumber;
}
Then I have another function down the line and I want to use the sum variable from function one
1 2 3 4 5 6 7 8 9
void functiontwo( void ){
int fourthnumber;
int fifthnumber;
int sixthnumber;
int totalsum = 0;
cout << "Enter the next three numbers: ";
cin >> fourthnumber >> fifthnumber >> sixthnumber;
totalsum = sum + fourthnumber + fifthnumber + sixthnumber;
}
How do I get sum from functionone and use it in functiontwo? I am having a hard time understanding the coding behind this.
My goal is to modularize the payroll program we have been working on using no global variables and to use pass by value and pass by reference to calculate everything. My book and instructor are not very helpful...
For that aim you have, it is not necessary to pass the value (here the sum) to functiontwo by reference -unless you want to change it's reference value. Anyway, you can use this way:
replace line 8 of first code to
int functionone(int initialSum)
{
int firstnumber, secondnumber, thirdnumber;
cout << "Enter three separate numbers: ";
cin >> firstnumber >> secondnumber >> thirdnumber;
return initialSum + firstNumber + secondNumber + thirdNumber;
}
Now you don't even need function2. You can use it like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int functionone(int initialSum = 0); // = 0 means that if no argument is given, it uses 0.
int main()
{
int Sum = functionone(); // Sum will output the sum of the first three numbersl
Sum = functionone(Sum); // Now we input three more numbers and add them to the running sum
}
int functionone(int initialSum)
{
int firstnumber, secondnumber, thirdnumber;
cout << "Enter three separate numbers: ";
cin >> firstnumber >> secondnumber >> thirdnumber;
return initialSum + firstNumber + secondNumber + thirdNumber;
}
If you want to pass by reference, you could do it this way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
void functionone(int& Sum)
{
int firstnumber, secondnumber, thirdnumber;
cout << "Enter three separate numbers: ";
cin >> firstnumber >> secondnumber >> thirdnumber;
Sum += firstNumber + secondNumber + thirdNumber;
}
int main()
{
int sum = 0;
functionone(sum); // This will add the initial three numbers to sum.
functionone(sum); // This will add three more numbers to sum
functionone(sum); // This will add three more numbers
}