Graphics Programs Reference
In-Depth Information
0x267
Variable Scoping
Another interesting concept regarding memory in C is variable scoping or
context—in particular, the contexts of variables within functions. Each func-
tion has its own set of local variables, which are independent of everything
else. In fact, multiple calls to the same function all have their own contexts.
You can use the printf() function with format strings to quickly explore this;
check it out in scope.c.
scope.c
#include <stdio.h>
void func3() {
int i = 11;
printf("\t\t\t[in func3] i = %d\n", i);
}
void func2() {
int i = 7;
printf("\t\t[in func2] i = %d\n", i);
func3();
printf("\t\t[back in func2] i = %d\n", i);
}
void func1() {
int i = 5;
printf("\t[in func1] i = %d\n", i);
func2();
printf("\t[back in func1] i = %d\n", i);
}
int main() {
int i = 3;
printf("[in main] i = %d\n", i);
func1();
printf("[back in main] i = %d\n", i);
}
The output of this simple program demonstrates nested function calls.
reader@hacking:~/booksrc $ gcc scope.c
reader@hacking:~/booksrc $ ./a.out
[in main] i = 3
[in func1] i = 5
[in func2] i = 7
[in func3] i = 11
[back in func2] i = 7
[back in func1] i = 5
[back in main] i = 3
r eader@hacking:~/booksrc $
Search WWH ::




Custom Search