Team LiB
Previous Section Next Section

6.1. Simple Statements

6.1. 简单语句

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

C++ 中,大多数语句以分号结束。例如,像 ival + 5 这样的表达式,在后面加上分号,就是一条表达式语句。表达式语句用于计算表达式。但执行下面的语句

     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.

循环条件从标准输入中读入一个值并检验 cin 的读入是否成功。如果成功读取数据,循环条件紧接着检查该值是否等于 sought。如果找到了需要的值,则退出 while 循环;否则,循环条件再次从 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:

whileif 条件后面额外添加分号,往往会彻底改变程序员的意图:

     // 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.


Team LiB
Previous Section Next Section