Section 6.1. Simple Statements


6.1. Simple Statements

Most statements in C++ end with a semicolon. An expression, such as ival + 5, becomes an expression statement by following it with a semicolon. Expression statements cause the expression to be evaluated. In the case of

      ival + 5;    // expression statement 

evaluating this expression is useless: The result is calculated but not assigned or otherwise used. More commonly, expression statements contain expressions that when evaluated affect the program's state. Examples of such expressions are those that use assignment, increment, input, or output operators.

Null Statements

The simplest form of statement is the empty, or null statement. It takes the following form (a single semicolon):

      ;  // null statement 

A null statement is useful where the language requires a statement but the program's logic does not. Such usage is most common when a loop's work can be done within the condition. For example, we might want to read an input stream, ignoring everything we read until we encounter a particular value:

      // read until we hit end-of-file or find an input equal to sought      while (cin >> s && s != sought)          ; // null statement 

The condition reads a value from the standard input and implicitly tests cin to see whether the read was successful. Assuming the read succeeded, the second part of the condition tests whether the value we read is equal to the value in sought. If we found the value we want, then the while loop is exited; otherwise, the condition is tested again, which involves reading another value from cin.

A null statement should be commented, so that anyone reading the code can see that the statement was omitted intentionally.



Because a null statement is a statement, it is legal anywhere a statement is expected. For this reason, semicolons that might appear illegal are often nothing more than null statements:

      // ok: second semicolon is superfluous null statement      ival = v1 + v2;; 

This fragment is composed of two statements: the expression statement and the null statement.

Extraneous null statements are not always harmless.



An extra semicolon following the condition in a while or if can drastically alter the programmer's intent:

      // disaster: extra semicolon: loop body is this null statement      while (iter != svec.end()) ; // null statement--while body is empty!          ++iter;     // increment is not part of the loop 

This program will loop indefinitely. Contrary to the indentation, the increment is not part of the loop. The loop body is a null statement caused by the extra semicolon following the condition.



C++ Primer
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2006
Pages: 223
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net