Comment

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


Puzzles SL01 ... SL10

Block Scope

These puzzles involve looking at code examples and predicting what will be written on the monitor. To do this, you need to figure out the scope of various variables.

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 down 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;  
}

An identifier has block scope when it appears inside a block or appears in the parameter list of a function definition. Syntactically, a block consists of statements enclosed by left and right braces, { and }. An identifer with block scope follows these rules:

  1. An identifier is visible inside its block from where it is declared to the end of the block.
  2. Blocks may be nested within blocks. An identifier declared in an outer block is visible in an inner block if the declaration preceeds the inner block.
  3. It is OK if the same identifier is declared in an outer block and is also declared in an inner block.
  4. When there are several blocks in sequence (nested in an outer block), the identifiers declared in one block cannot be seen in another block.
  5. The parameters of a function have block scope for the body of the function (which is a block).


Next Page         Home