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;
¹
└────── }