C requires you to declare variables at the beginning of a block. C++ allows you to declare a variable anywhere in the code, as long as you declare it before you reference it. This feature lets you place the declaration of a variable closer to the code that uses it, making the program more readable.
The following example shows how you can position the declaration of a variable near its first reference.
// Declaring a variable near its first reference
#include <iostream.h>
void main()
{
cout << "Enter a number: ";
int n;
cin >> n;
cout << "The number is: " << n;
}
The freedom to declare a variable anywhere in a block makes expressions such as the following one possible:
for( int ctr = 0; ctr < MAXCTR; ctr++ )
However, you cannot have expressions like the following:
if( int i == 0 ) // Error
;
while( int j == 0 ) // Error
;
Such expressions are meaningless, since there is no need to test the value of a variable the moment it is declared.
The following example declares a variable in a block.
// Variable declaration placement
#include <iostream.h>
void main()
{
for( int lineno = 0; lineno < 3; lineno++ )
{
int temp = 22;
cout << "\nThis is line number " << lineno
<< "and temp is " << temp;
}
if( lineno == 4 ) // lineno still accessible
cout << "\nOops";
// Cannot access temp
}
This example produces the following output:
This is line number 0 and temp is 22
This is line number 1 and temp is 22
This is line number 2 and temp is 22
Note that the two variables lineno and temp have different scopes. The lineno variable is in scope for the current block (in this case, until main ends) and all blocks subordinate to the current one. Its scope, however, begins where the declaration appears. C++ statements that appear before a variable's declaration cannot refer to the variable even though they appear in the same block. The temp variable, however, goes out of scope when the for loop ends. It is accessible only from within the loop.
You should exercise care when declaring variables in places other than the beginning of a block. If you scatter declarations haphazardly throughout your program, a person reading your program may have difficulty finding where a variable is declared.