Views
This is a scratchpad to work out examples of how scope works in C.
Levels
-
global
-
file (i.e. static functions/variables)
-
function
-
block (i.e. within brackets)
Preprocessor definitions
-
#define and #include is per-file
-
#include imports other #defines and #includes into the file
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