Chapter 4 StatementsStatements define and control what a program does. This chapter describes the syntax and rules for C++ statements: expressions, loops, selection, and control. The statement syntax rules apply recursively, and wherever a statement is called for, you can use (almost) any of the statements in this chapter.The syntax descriptions in this chapter are informal. See Chapter 12 for a precise BNF grammar.Expression StatementsAn expression statement computes an expression, such as a function call or assignment. The expression result is discarded, so the expression is typically evaluated for its side effects. (See Chapter 3 for details about expressions.) The statement syntax is simply an optional expression followed by a semicolon:expr ;or:;A statement with no expression is called a null statement. Null statements are most often used for loops when no code is needed in the loop body.Here are several examples of expression statements:42; // Valid but pointlesscout << 42; // More typicalx = y * z; // Remember that assignment is an expression; // Null statementDeclarationsA 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 StatementsA 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.
ASIN : 059600298X
Binding : Paperback
EAN : 9780596002985
Edition : 1
Feature :
ISBN : 059600298X
Label : O'Reilly Media
Languages :
Manufacturer : O'Reilly Media
Number of Pages : 810
Publication Date : 15 May 2003
SKU : I9780596002985
Studio : O'Reilly Media