The following example declares the variable x on line 1, which is different from the x it declares on line 2. The declared variable on line 2 has function prototype scope and is visible only up to the closing parenthesis of the prototype declaration. The variable x declared on line 1 resumes visibility after the end of the prototype declaration.
1 int x = 4; /* variable x defined with file scope */
2 long myfunc(int x, long y); /* variable x has function */
3 /* prototype scope */
4 int main(void)
5 {
6 /* . . . */
7 }
The following program illustrates blocks, nesting, and scope. The example shows two kinds of scope: file and block. The main function prints the values 1, 2, 3, 0, 3, 2, 1 on separate lines. Each instance of i represents a different variable.
#include <stdio.h> int i = 1; /* i defined at file scope */ int main(int argc, char * argv[]) *----- { ¹ ¹ printf("%d\n", i); /* Prints 1 */ ¹ ¹ *--- { ¹ ² int i = 2, j = 3; /* i and j defined at block scope */ ¹ ² /* global definition of i is hidden */ ¹ ² printf("%d\n%d\n", i, j); /* Prints 2, 3 */ ¹ ² ¹ ² *-- { ¹ ² ³ int i = 0; /* i is redefined in a nested block */ ¹ ² ³ /* previous definitions of i are hidden */ ¹ ² ³ printf("%d\n%d\n", i, j); /* Prints 0, 3 */ ¹ ² *-- } ¹ ² ¹ ² printf("%d\n", i); /* Prints 2 */ ¹ ² ¹ *--- } ¹ ¹ printf("%d\n", i); /* Prints 1 */ ¹ ¹ return 0; ¹ *------ }