Function/Variable Scope   «Prev  Next»
Lesson 6 Scope
Objective Write an output function for the course project.

C++ File local Scope

C++ has two principal forms of scope:
  1. file scope
  2. local scope.
and Local scope is scoped to a block. File scope has names that are external (global).
In C++, declarations can be internal to a block. In Standard C, all block scope declarations occur at the head of the block.


Here is an example of C++ declarations within a block:
//C++ but not C

int max(int c[], int size){
 cout << "array size is " << size << endl;
 int  comp = c[0];           //declaration of comp
 for (int i = 1; i < size; ++i) //declaration of i
  if (c[i] > comp)
 comp = c[i];
  return comp;

In C++, the scope of an identifier begins at the end of its declaration and continues to the end of its innermost enclosing block.

Declarations in small blocks

For small blocks, it is generally good programming practice to place declarations at the head of a block. This provides good documentation.

Declarations in large blocks

For large blocks, it is best to place declarations as close as possible to where they are used. This allows computed or inputted values to initialize a variable.

Project Output - Exercise

Click the Exercise link below to write an output function for the course project.
Project Output - Exercise