Comment

revised: 01/06/2008, 06/24/2017


Puzzles SL11 ... SL20

Block Scope and File Scope

The scope of an identifier is the section of the source file in which the identifier may be used. C compilers start at the top of a source file and work line by line until they reach the end. Because of this, an identifier definition must appear earlier in a source file than any statement that uses it. (This is unlike Java and some other languages.)

An identifier has block scope if it is declared inside a block. Also, the parameters of a function have block scope for the block that is the body of the function.

An identifier has file scope if it is declared outside of any block or parameter list.

An identifier with file scope is visible from where it is declared in its file down to the end of the file, except within blocks that use the same identifier in a parameter list or a declaration.

The names of functions have file scope, so a function name is visible from where it is defined to the end of the file.

The following would compile. variable a has file scope.

#include <stdio.h>
int a = 7;
int main()
{
  a = a+5;
  printf("%d\n", a );
}

The following would not compile (because of one-pass compiling):

#include <stdio.h>

int main()
{
  a = a+5;
  printf("%d\n", a );
}
int a = 7;

The following puzzles involve code where some variables have block scope and others have file scope.



Next Page         Home