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. This behavior one-pass compiling. 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.) The following would not compile because when the compiler reaches the assignment statement, it has not seen a.

int main()
{
  a = 7;
  
  int a;
}

The following would compile:

int main()
{
  int a;

  a = 7;  
}

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

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.



Next Page         Home