Examples of scope in C

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[])
 *-----     {
 1
 1             printf("%d\n", i);              /* Prints 1 */
 1
 1  *---       {
 1  2             int i = 2, j = 3;            /* i and j defined at
 1  2                                             block scope */
 1  2             printf("%d\n%d\n", i, j);    /* Prints 2, 3 */
 1  2
 1  2 *--         {
 1  2 3              int i = 0;  /* i is redefined in a nested block */
 1  2 3                          /* previous definitions of i are hidden */
 1  2 3              printf("%d\n%d\n", i, j); /* Prints 0, 3 */
 1  2 *--         }
 1  2
 1  2             printf("%d\n", i);           /* Prints 2 */
 1  2
 1  *---       }
 1
 1             printf("%d\n", i);              /* Prints 1 */
 1
 1             return 0;
 1
 *------   }