Académique Documents
Professionnel Documents
Culture Documents
20070110 chap13
auto: Simple variables in a function block. Scope is limited to the function/block in which the variable is declared. Visible ONLY inside a function or block and exists only while the function/block is active.
20070110 chap13
Global Variables
A variable that may be accessed by many functions in a program.
/* eg1.c */ int global_var_x; void afun(int n) /* eg2.c */ extern int global_var_x; void bfun(int n)
Only the defining declaration, the one in eg1.c, allocates spaces for global_var_x. A declaration beginning with the keyword extern allocated no memory; it simply provides information for the computer.
20070110 chap13 4
Output:
Output:
20070110 chap13
Static Variables
static: storage class of variables allocated only once, prior to program execution.
int fun_frag(int n) { static int once = 0; int many = 0;
many is allocated space on the stack each time fun_frag is called. Every time fun_frag returns, many is deallocated. Static variable once is allocated and initialized one time, prior to program execution. It remains allocated until the entire program terminates.
20070110 chap13 8
Register variables
Storage class of automatic variable that the programmer would like to have stored in registers. It is closely related to storage class auto and may be applied only to local variables and parameters. By choosing storage class register, the programmer indicates an expectation that the program would run faster if a register, a special high-speed memory location inside the central processor, could be used for the variable.
20070110 chap13
E.g:
int foo () { static int x; x++; return x; }
Notes on extern
E.g: file ext.c
# include <stdio.h> int main () { extern int y; printf ("%d\n", y); }
Notes on register
register:
Use of address operator (&) is ignored (as it is meaningless). Register variables can produce faster code since their values are not retrieved from memory (RAM). Frequently, optimizing compilers will generate register variables automatically.