Graphics Programs Reference
In-Depth Information
[in func1] i = 5, j = 42
[in func2] i = 7, j = 42
[in func2] setting j = 1337
[in func3] i = 11, j = 999
[back in func2] i = 7, j = 1337
[back in func1] i = 5, j = 1337
[back in main] i = 3, j = 1337
reader@hacking:~/booksrc $
In the output, the global variable j is written to in func2() , and the
change persists in all functions except func3() , which has its own local
variable called j . In this case, the compiler prefers to use the local variable.
With all these variables using the same names, it can be a little confusing, but
remember that in the end, it's all just memory. The global variable j is just
stored in memory, and every function is able to access that memory. The local
variables for each function are each stored in their own places in memory,
regardless of the identical names. Printing the memory addresses of these
variables will give a clearer picture of what's going on. In the scope3.c example
code below, the variable addresses are printed using the unary address-of
operator.
scope3.c
#include <stdio.h>
int j = 42; // j is a global variable.
void func3() {
int i = 11, j = 999; // Here, j is a local variable of func3().
printf("\t\t\t[in func3] i @ 0x%08x = %d\n", &i, i);
printf("\t\t\t[in func3] j @ 0x%08x = %d\n", &j, j);
}
void func2() {
int i = 7;
printf("\t\t[in func2] i @ 0x%08x = %d\n", &i, i);
printf("\t\t[in func2] j @ 0x%08x = %d\n", &j, j);
printf("\t\t[in func2] setting j = 1337\n");
j = 1337; // Writing to j
func3();
printf("\t\t[back in func2] i @ 0x%08x = %d\n", &i, i);
printf("\t\t[back in func2] j @ 0x%08x = %d\n", &j, j);
}
void func1() {
int i = 5;
printf("\t[in func1] i @ 0x%08x = %d\n", &i, i);
printf("\t[in func1] j @ 0x%08x = %d\n", &j, j);
func2();
printf("\t[back in func1] i @ 0x%08x = %d\n", &i, i);
printf("\t[back in func1] j @ 0x%08x = %d\n", &j, j);
}
Search WWH ::




Custom Search