home changes contents help options

This is a scratchpad to work out examples of how scope works in C.

Levels

Preprocessor definitions

Variables

With variables, symbols declared at or above the current level are visible:

int myGlobalInt;           /* global */
static myGlobalPerFileInt; /* file */
void myFunction(void() {   
    int myFunctionInt;     /* function */
    {
        int myInt;         /* block */
    }
}

#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 */
        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;
}

References