Lesson 6 | Scope |
Objective | Write an output function for the course project. |
C++ File local Scope
Example
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