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.»
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;
}