Returning values from a void to integer

So, I was reading a book and it said if I had a limited variable (not a global variable) from a void, I could also use it in an integer without making it a global variable.

«An elegant way of having the result of multiplication in main() as
required in Listing 3.3 is to have MultiplyNumbers() return that
result to main.»

The code was:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1: #include <iostream>
2: using namespace std;
3:
4: void MultiplyNumbers ()
5: {
6: cout << “Enter the first number: “;
7: int FirstNumber = 0;
8: cin >> FirstNumber;
9:
10: cout << “Enter the second number: “;
11: int SecondNumber = 0;
12: cin >> SecondNumber;
13:
14: // Multiply two numbers, store result in a variable
15: int MultiplicationResult = FirstNumber * SecondNumber;
16:
17: // Display result
18: cout << FirstNumber << “ x “ << SecondNumber;
19: cout << “ = “ << MultiplicationResult << endl;
20: }
21: int main ()
22: {
23: cout << “This program will help you multiply two numbers” << endl;
24:
25: // Call the function that does all the work
26: MultiplyNumbers();
27:
28: // cout << FirstNumber << “ x “ << SecondNumber;
29: // cout << “ = “ << MultiplicationResult << endl;
30:
31: return 0;
32: }


How can I do that?
Thanks in advance
Last edited on
i read this:

«An elegant way of having the result of multiplication in main() as
required in Listing 3.3 is to have MultiplyNumbers() return that
result to main.»

as the author implying you change your void function to an int function, and return the value of you 'MultiplicationResult' variable.


it said if I had a limited variable (not a global variable) from a void, I could also use it in an integer without making it a global variable.

I have no idea what this means.
I think what you are talking about is using return values instead of void functions.

Take this code:
1
2
3
4
5
6
7
8
9
10
11
12
int a, b, c; // globals

void multiply() { // drives globals
  c = a * b;
}

int main() {
  a = 1; b = 2;
  multiply(); // not clear here that c is driven
  std::cout << "c is: " << c;
  return 0;
}


Here we use a void function and global variables to do things. Unfortunately, this means "multiply" can only be used in this one context and we can't re-use it or the other variables without possibly changing some other part fo the code. By making this an "int" function instead we can make the function much more generic, safe, and avoid globals:
1
2
3
4
5
6
7
8
9
10
int multiply(int x, int y) { // returns int
  return x * y; // generic function, can be reused.
}

int main() {
  int a = 1, b = 2, c; // abc are local
  c = multiply(a,b); // we understand c is a function of a,b
  std::cout << "c is: " << c; 
  return 0;
}
Last edited on
Thank you Mutexe and Stewbond for your replies, they really helped me.
Topic archived. No new replies allowed.