posted 12 years ago
First off, yes, moving line 24 to line 2 would make the code compile because it would make the variable h a global variable.
But to address the original question more specifically, let me state that one variable can access a variable in another function WHEN YOU PASS THE ADDRESS BETWEEN FUNCTIONS. There are plenty of examples of this in Chapter 6 of my book I believe.
For example, I have a value, i, set to 10, stored in variable i in one furnction. By passing the address of i (notated as &i) to function #2, I give function #2 access to the original variable, i... That is, furnction #2 can actually make permanent changes to the value of i...
void funct1() {
int i = 10;
"value of i before call is " << i << endl; // prints 10
funct2(&i);
"value of i after call is " << i << endl; // prints 20
}
void funct2(int *n) {
*n = *n * 2; // Double the value
}
Note that this does not work if you pass i directly, because argument values passed to a function are just thrown away. But function 2 uses a pointer to gain access to the original copy of i rather than just working on its own copy.
This is explained in much much greater depth in my books.
Brian Overland