Declarations
A declaration can appear anywhere a statement appears, and certain statements permit additional declarations within those statements.
Declarations made in a substatement (of a selection or loop statement) are limited in scope to the substatement, even if the substatement is not a compound statement. For example, the following statement:
while ( test( ) ) int x = init( );
is equivalent to:
while ( test( ) ) {
int x = init( );
}The first example uses a declaration as the entire loop body, and
the second uses a compound statement (enclosing the loop body in curly
braces). In both cases, though, the scope of x is limited to the body of the while loop.
Declaration Statements
A simple declaration can appear wherever a statement can be
used. You can declare an object, a type, or a namespace alias. You can
also write a using declaration or
using directive. You can declare a
function, but not define a function, although there is rarely any
reason to declare a function locally. You cannot define a namespace or
declare a template.
In traditional C programming, declarations appear at the start of each block or compound statement. In C++ (and in the C99 standard), declarations can appear anywhere a statement can, which means you can declare variables close to where they are used. Example 4-1 shows examples of how declarations can be mixed with statements.
#include <cctype> #include <cstddef> #include <iomanip> #include <iostream> #include ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access