Okay, I posted a very similar code block a few days ago and got some good responses, but still can't quite understand the logic of going from a variable and then pass by reference the variable as a parameter in a function.
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
int getData();
void displayMenu(int & menuChoice);
void processMenuChoice(int & menuChoice, int answer);
void isPosNeg();
void isOddEven();
int main()
{
int menuChoice = 0;
displayMenu(menuChoice);
cout << "You entered " << getData();
cout << "You selected" << result;
return 0;
}
int getData()
{
int number;
cout << "Please enter a number: ";
cin >> number;
while (number < -1000000 || number > 1000000) {
cout << "Error. Please enter a valid number."
<< "\nPlease enter a number: ";
cin >> number;
}
return number;
}
void displayMenu(int & menuChoice)
{
cout << "\n1) Is the number odd or even?\n"
<< "2) Is the number positive or negative?\n"
<< "3) What is the square root of the number?\n"
<< "4) How many digits are in the number?\n"
<< "5) Digit Extraction.\n"
<< "6) Display Addition Table.\n"
<< "7) Display Multiplication Table.\n"
<< "8) Exit\n";
int menuChoice = 0;
cout << "\nEnter a menu choice: ";
cin >> menuChoice;
}
void processMenuChoice(int menuChoice, int & answer)
{
switch (menuChoice)
{
case 1:
isPosNeg();
break;
case 2:
isOddEven();
break;
}
}
void isPosNeg( int answer)
{
int answer = getData();
if (answer > 0)
cout << "The number is positive!\n";
elseif (answer < 0)
cout << "The number is negative!\n";
elseif (answer == 0)
cout << "The number you entered was a zero and is neither positive or negative\n";
}
void isOddEven()
{
int answer = getData();
if (answer % 2 == 0 && answer != 0)
cout << "The number is even.\n";
elseif (answer % 2 == 1)
cout << "The number is odd.\n";
elseif (answer == 0)
cout << "The number you entered is a 0 and is not even or odd.\n";
}
The point when passing a variable by [non const] reference is that the value can be modified and that modification remains after the function has finished. I.e. the caller can do somthing with the modified variable. That's the point here.
On line 49 you shadow the paramter menuChoice. That is the paramter is not changed but the local variable. So that the parameter make sense you need to remove line 48.
The same applies to answer in processMenuChoice(...). You need to remove int in front of answer on line 69/80.
To use this main(...) migth look like:
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
int menuChoice = 0;
displayMenu(menuChoice); // Note: menuChoice is modified after displayMenu(...) is called because it is passed by reference
int answer = 0;
processMenuChoice(menuChoice, answer); // Note: answer is modified after processMenuChoice(...) is called. Whereas menuChoice remains unchanged because it is passed by value
processAnswer(answer);
...
return 0;
}