0

How do you properly get a variable to update when used as a parameter in a function that is being called the main function?

#include "iostream"

int getUserNumber (int input) {
    std::cout << "Please input an integer: ";
    std::cin >> input;
    return input;
}

int main () {
    std::cout << "testing getUserNumber function\n";
    int a = 104;
    getUserNumber(a);
    std::cout << "\n" << a << "\n";
    return 0;
}

Whenever I print "a" to test the value, it does not equal what is entered into the console and only returns the value of 104 that it was initially equated to. I am looking for "a" to update from inputted integers such as "6" by using the getUserNumber. Thank you for reviewing my code.

  • There are some great working examples of code below. In order to understand why their code works and yours does not, this is a great resource: (https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) – Braden W Feb 05 '19 at 04:47
  • Thanks for the references. I did not even know the terminology, but now can read on the topic. – Ripped Gorrila Feb 05 '19 at 05:08

2 Answers2

2

You can use returned int.

something like..

int getUserNumber () {
    int input;
    std::cout << "Please input an integer: ";
    std::cin >> input;
    return input;
}

in main() { 
...
    int a = getUserNumber();
...
}
Andy
  • 377
  • 6
  • 10
0
#include "iostream"

int getUserNumber () {
    int input;
    std::cout << "Please input an integer: ";
    std::cin >> input;
    return input;
}

int main () {
    std::cout << "testing getUserNumber function\n";
    int a = getUserNumber();
    std::cout << "\n" << a << "\n";
    return 0;
}

Linked duplicate questions does explain why it works this way. They are technically correct but can be a bit overwhelming. Let me try to explain.

When designing a function, you have to ask yourselves the following questions

  1. What does the function needs from its caller? caller is the calling function, i.e. main.
  2. What does the function gives back?

For example, consider a function called printANumber

  1. It needs to know what to print,
  2. It has nothing to return to its caller (main function).

So, the signature is

void printANumber(int number) // void here means nothing.

Now, getUserNumber,

  1. does not need anything from its caller ( it gets the number from the user via console. Not via main function). So it should not have any parameters.
  2. And it should give back the number it got from the user to the main function, which can do anything with it. Like print it, add it, save it etc,

So the signature should be:

int getUserNumber()

If function needs something and gives back something you have both parameters and return value. E.g.

int add(int number1, int number2) // return value is the sum of both numbers
balki
  • 26,394
  • 30
  • 105
  • 151