1.4. Control Structures 1.4. 控制结构 Statements execute sequentially: The first statement in a function is executed first, followed by the second, and so on. Of course, few programsincluding the one we'll need to write to solve our bookstore problemcan be written using only sequential execution. Instead, programming languages provide various control structures that allow for more complicated execution paths. This section will take a brief look at some of the control structures provided by C++. Chapter 6 covers statements in detail. 语句总是顺序执行的:函数的第一条语句首先执行,接着是第二条,依次类推。当然,少数程序——包括我们将要编写的解决书店问题的程序——可以仅用顺序执行语句编写。事实上,程序设计语言提供了多种控制结构支持更为复杂的执行路径。本节将简要地介绍 C++ 提供的控制结构,第六章再详细介绍各种语句。 1.4.1. The while Statement 1.4.1. while 语句 A while statement provides for iterative execution. We could use a while to write a program to sum the numbers from 1 through 10 inclusive as follows: while 语句提供了迭代执行功能。可以用 while 语句编写一个如下所示的从 1 到 10(包括 10)的求和程序: #include <iostream> int main() { int sum = 0, val = 1; // keep executing the while until val is greater than 10 while (val <= 10) { sum += val; // assigns sum + val to sum ++val; // add 1 to val } std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl; return 0; } This program when compiled and executed will print: 编译并执行后,将输出: Sum of 1 to 10 inclusive is 55 As before, we begin by including the iostream header and define a main function. Inside main we define two int variables: sum, which will hold our summation, and val, which will represent each of the values from 1 through 10. We give sum an initial value of zero and start val off with the value one. 与前面一样,程序首先包含 iostream 头文件并定义 main 函数。在 main 函数中定义两个 int 型变量:sum 保存总和,val 表示从 1 到 10 之间的每一个值。我们给 sum 赋初值 0,而 val 则从 1 开始。 The important part is the while statement. A while has the form 重要的部分是 while 语句。while 结构有这样的形式: while (condition) while_body_statement; A while executes by (repeatedly) testing the condition and executing the associated while_body_statement until the condition is false. while 通过测试 condition (条件)和执行相关 while_body_statement 来重复执行,直到 condition 为假。 A condition is an expression that is evaluated so that its result can be tested. If the resulting value is nonzero, then the condition is true; if the value is zero then the condition is false. 条件是一个可求值的表达式,所以可以测试其结果。如果结果值非零,那么条件为真;如果值为零,则条件为假。 If the condition is true (the expression evaluates to a value other than zero) then while_body_statement is executed. After executing while_body_statement, the condition is tested again. If condition remains true, then the while_body_statement is again executed. The while continues, alternatively testing the condition and executing while_body_statement until the condition is false. 如果 condition 为真(表达式求值不为零),则执行 while_body_statement。执行完后,再次测试 condition 。如果 condition 仍为真,则再次执行 while_body_statement。while 语句一直交替测试 condition 和执行 while_body_statement,直到 condition 为假为止。 In this program, the while statement is: 在这个程序中,while 语句是 // keep executing the while until val is greater than 10 while (val <= 10) { sum += val; // assigns sum + val to sum ++val; // add 1 to val } The condition in the while uses the less-than-or-equal operator (the <= operator) to compare the current value of val and 10. As long as val is less than or equal to 10, we execute the body of the while. In this case, the body of the while is a block containing two statements: while 语句的条件用了小于或等于操作符(<= 操作符),将 val 的当前值和 10 比较,只要 val 小于或等于 10,就执行 while 循环体。这种情况下,while 循环体是一个包含两个语句的块: { sum += val; // assigns sum + val to sum ++val; // add 1 to val } A block is a sequence of statements enclosed by curly braces. In C++, a block may be used wherever a statement is expected. The first statement in the block uses the compound assignment operator, (the += operator). This operator adds its right-hand operand to its left-hand operand. It has the same effect as writing an addition and an assignment: 块是被花括号括起来的语句序列。C++ 中,块可用于任何可以用一条语句的地方。块中第一条语句使用了复合赋值操作符(+= 操作符),这个操作符把它的右操作数加至左操作数,这等效于编写含一个加法和一个赋值的语句: sum = sum + val; // assign sum + val to sum Thus, the first statement adds the value of val to the current value of sum and stores the result back into sum. 因此第一条语句是把 val 的值加到 sum 的当前值,并把结果存入 sum。 The next statement 第二条语句 ++val; // add 1 to val uses the prefix increment operator (the ++ operator). The increment operator adds one to its operand. Writing ++val is the same as writing val = val + 1. 使用了前自增操作符(++ 操作符),自增操作符就是在它的操作数上加 1,++val 和 val = val + 1 是一样的。 After executing the while body we again execute the condition in the while. If the (now incremented) value of val is still less than or equal to 10, then the body of the while is executed again. The loop continues, testing the condition and executing the body, until val is no longer less than or equal to 10. 执行 while 的循环体后,再次执行 while 的条件。如果 val 的值(自增后)仍小于或等于 10,那么再次执行 while 的循环体。循环继续,测试条件并执行循环体,直到 val 的值不再小于或等于 10 为止。 Once val is greater than 10, we fall out of the while loop and execute the statement following the while. In this case, that statement prints our output, followed by the return, which completes our main program. 一旦 val 的值大于 10,程序就跳出 while 循环并执行 while 后面的语句,此例中该语句打印输出,其后的 return 语句结束 main 程序。 C++ programs are largely free-format, meaning that the positioning of curly braces, indentation, comments, and newlines usually has no effect on the meaning of our programs. For example, the curly brace that denotes the beginning of the body of main could be on the same line as main, positioned as we have done, at the beginning of the next line, or placed anywhere we'd like. The only requirement is that it be the first nonblank, noncomment character that the compiler sees after the close parenthesis that concludes main's parameter list. C++ 程序的格式非常自由,花括号、缩排、注释和换行的位置通常对程序的语义没有影响。例如,表示 main 函数体开始的花括号可以放在与 main 同一行,也可以像我们那样,放在下一行的开始,或放在你喜欢的任何地方。唯一的要求是,它是编译器所看到在 main 的参数列表的右括号之后的第一个非空格、非注释字符。 Although we are largely free to format programs as we wish, the choices we make affect the readability of our programs. We could, for example, have written main on a single, long line. Such a definition, although legal, would be hard to read. 虽然说我们可以很自由地编排程序的格式,但如果编排不当,会影响程序的可读性。例如,我们可以将 main 写成单独的一长行。这样的定义尽管合法,但很难阅读。 Endless debates occur as to the right way to format C or C++ programs. Our belief is that there is no single correct style but that there is value in consistency. We tend to put the curly braces that delimit functions on their own lines. We tend to indent compound input or output expressions so that the operators line up, as we did with the statement that wrote the output in the main function on page 6. Other indentation conventions will become clear as our programs become more complex. 关于什么是 C 或 C++ 程序的正确格式存在无休止的争论,我们相信没有唯一正确的风格,但一致性是有价值的。我们倾向于把确定函数边界的花括号自成一行,且缩进复合的输入或输出表达式从而使操作符排列整齐,正如第 1.2.2 节的 main 函数中的输出语句那样。随着程序的复杂化,其他缩排规范也会变得清晰。 The important thing to keep in mind is that other ways to format programs are possible. When choosing a formatting style, think about how it affects readability and comprehension. Once you've chosen a style, use it consistently. 可能存在其他格式化程序的方式,记住这一点很重要。在选择格式化风格时,要考虑提高程序的可读性,使其更易于理解。一旦选择了某种风格,就要始终如一地使用。 | 1.4.2. The for Statement 1.4.2. for 语句 In our while loop, we used the variable val to control how many times we iterated through the loop. On each pass through the while, the value of val was tested and then in the body the value of val was incremented. 在 while 循环中,我们使用变量 val 来控制循环执行次数。每次执行 while 语句,都要测试 val 的值,然后在循环体中增加 val 的值。 The use of a variable like val to control a loop happens so often that the language defines a second control structure, called a for statement, that abbreviates the code that manages the loop variable. We could rewrite the program to sum the numbers from 1 through 10 using a for loop as follows: 由于需要频频使用像 val 这样的变量控制循环,因而 C++ 语言定义了第二种控制结构,称为 for 语句,简化管理循环变量的代码。使用 for 循环重新编写求 1 到 10 的和的程序,如下: #include <iostream> int main() { int sum = 0; // sum values from 1 up to 10 inclusive for (int val = 1; val <= 10; ++val) sum += val; // equivalent to sum = sum + val std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl; return 0; } Prior to the for loop, we define sum, which we set to zero. The variable val is used only inside the iteration and is defined as part of the for statement itself. The for statement 在 for 循环之前,我们定义 sum 并赋 0 值。用于迭代的变量 val 被定义为 for 语句自身的一部分。for 语句 for (int val = 1; val <= 10; ++val) sum += val; // equivalent to sum = sum + val has two parts: the for header and the for body. The header controls how often the body is executed. The header itself consists of three parts: an init-statement, a condition, and an expression. In this case, the init-statement 包含 for 语句头和 for 语句体两部分。for 语句头控制 for 语句体的执行次数。for 语句头由三部分组成:一个初始化语句,一个条件,一个表达式。在这个例子中,初始化语句 int val = 1; defines an int object named val and gives it an initial value of one. The initstatement is performed only once, on entry to the for. The condition 定义一个名为 val 的 int 对象并给定初始值 1。初始化语句仅在进入 for 语句时执行一次。条件 val <= 10 which compares the current value in val to 10, is tested each time through the loop. As long as val is less than or equal to 10, we execute the for body. Only after executing the body is the expression executed. In this for, the expression uses the prefix increment operator, which as we know adds one to the value of val. After executing the expression, the for retests the condition. If the new value of val is still less than or equal to 10, then the for loop body is executed and val is incremented again. Execution continues until the condition fails. 将 val 的当前值和 10 比较,每次经过循环都要测试。只要 val 小于或等于 10,就执行 for 语句体。仅当 for 语句体执行后才执行表达式。在这个 for 循环中,表达式使用前自增操作符,val 的值加 1,执行完表达式后,for 语句重新测试条件,如果 val 的新值仍小于或等于 10,则执行 for 语句体,val 再次自增,继续执行直到条件不成立。 In this loop, the for body performs the summation 在这个循环中,for 语句体执行求和 sum += val; // equivalent to sum = sum + val The body uses the compound assignment operator to add the current value of val to sum, storing the result back into sum. for 语句体使用复合赋值操作符,把 val 的当前值加到 sum,并将结果保存到 sum 中。 To recap, the overall execution flow of this for is: 扼要重述一下,for 循环总的执行流程为: -
Create val and initialize it to 1. 创建 val 并初始化为 1。 -
Test whether val is less than or equal to 10. 测试 val 是否小于或等于 10。 -
If val is less than or equal to 10, execute the for body, which adds val to sum. If val is not less than or equal to 10, then break out of the loop and continue execution with the first statement following the for body. 如果 val 小于或等于 10,则执行 for 循环体,把 val 加到 sum 中。如果 val 大于 10,就退出循环,接着执行 for 语句体后的第一条语句。 -
-
Repeat the test in step 2, continuing with the remaining steps as long as the condition is true. 重复第 2 步的测试,只要条件为真,就继续执行其余步骤。 | When we exit the for loop, the variable val is no longer accessible. It is not possible to use val after this loop terminates. However, not all compilers enforce this requirement. 退出 for 循环后,变量 val 不再可访问,循环终止后使用 val 是不可能的。然而,不是所有的编译器都有这一要求。 | In pre-Standard C++ names defined in a for header were accessible outside the for itself. This change in the language definition can surprise people accustomed to using an older compiler when they instead use a compiler that adheres to the standard. 在标准化之前的 C++ 中,定义在 for 语句头的名字在 for 循环外是可访问的。语言定义中的这一改变,可能会使习惯于使用老式编译器的人,在使用遵循标准的新编译器时感到惊讶。 Part of the compiler's job is to look for errors in the program text. A compiler cannot detect whether the meaning of a program is correct, but it can detect errors in the form of the program. The following are the most common kinds of errors a compiler will detect. 编译器的部分工作是寻找程序代码中的错误。编译器不能查出程序的意义是否正确, 但它可以查出程序形式上的错误。下面是编译器能查出的最普遍的一些错误。 -
Syntax errors. The programmer has made a grammatical error in the C++ language. The following program illustrates common syntax errors; each comment describes the error on the following line: 语法错误。程序员犯了 C++ 语言中的语法错误。下面代码段说明常见的语法错误;每个注释描述下一行的错误。 // error: missing ')' in parameter list for main int main ( { // error: used colon, not a semicolon after endl std::cout << "Read each file." << std::endl: // error: missing quotes around string literal std::cout << Update master. << std::endl; // ok: no errors on this line std::cout << "Write new master." <<std::endl; // error: missing ';' on return statement return 0 } -
Type errors. Each item of data in C++ has an associated type. The value 10, for example, is an integer. The word "hello" surrounded by double quotation marks is a string literal. One example of a type error is passing a string literal to a function that expects an integer argument. 类型错误。C++ 中每个数据项都有其相关联的类型。例如,值 10 是一个整数。用双引号标注起来的单词“hello”是字符串字面值。类型错误的一个实例是传递了字符串字面值给应该得到整型参数的函数。 -
Declaration errors. Every name used in a C++ program must be declared before it is used. Failure to declare a name usually results in an error message. The two most common declaration errors are to forget to use std:: when accessing a name from the library or to inadvertently misspell the name of an identifier: 声明错误。C++ 程序中使用的每个名字必须在使用之前声明。没有声明名字通常会导致错误信息。最常见的两种声明错误,是从标准库中访问名字时忘记使用“std::”,以及由于疏忽而拼错标识符名: #include <iostream> int main() { int v1, v2; std::cin >> v >> v2; // error: uses " v "not" v1" // cout not defined, should be std::cout cout << v1 + v2 << std::endl; return 0; } An error message contains a line number and a brief description of what the compiler believes we have done wrong. It is a good practice to correct errors in the sequence they are reported. Often a single error can have a cascading effect and cause a compiler to report more errors than actually are present. It is also a good idea to recompile the code after each fixor after making at most a small number of obvious fixes. This cycle is known as edit-compile-debug. 错误信息包含行号和编译器对我们所犯错误的简要描述。按错误报告的顺序改正错误是个好习惯,通常一个错误可能会产生一连串的影响,并导致编译器报告比实际多得多的错误。最好在每次修改后或最多改正了一些显而易见的错误后,就重新编译代码。这个循环就是众所周知的编辑—编译—调试。 | Exercise 1.9: | What does the following for loop do? What is the final value of sum? 下列循环做什么?sum 的最终值是多少? int sum = 0; for (int i = -100; i <= 100; ++i) sum += i; | Exercise 1.10: | Write a program that uses a for loop to sum the numbers from 50 to 100. Now rewrite the program using a while. 用 for 循环编程,求从 50 到 100 的所有自然数的和。然后用 while 循环重写该程序。 | Exercise 1.11: | Write a program using a while loop to print the numbers from 10 down to 0. Now rewrite the program using a for. 用 while 循环编程,输出 10 到 0 递减的自然数。然后用 for 循环重写该程序。 | Exercise 1.12: | Compare and contrast the loops you wrote in the previous two exercises. Are there advantages or disadvantages to using either form? 对比前面两个习题中所写的循环。两种形式各有何优缺点? | Exercise 1.13: | Compilers vary as to how easy it is to understand their diagnostics. Write programs that contain the common errors discussed in the box on 16. Study the messages the compiler generates so that these messages will be familiar when you encounter them while compiling more complex programs. 编译器不同,理解其诊断内容的难易程度也不同。编写一些程序,包含本小节“再谈编译”部分讨论的那些常见错误。研究编译器产生的信息,这样你在编译更复杂的程序遇到这些信息时就不会陌生。 | | 1.4.3. The if Statement 1.4.3. if 语句 A logical extension of summing the values between 1 and 10 is to sum the values between two numbers our user supplies. We might use the numbers directly in our for loop, using the first input as the lower bound for the range and the second as the upper bound. However, if the user gives us the higher number first, that strategy would fail: Our program would exit the for loop immediately. Instead, we should adjust the range so that the larger number is the upper bound and the smaller is the lower. To do so, we need a way to see which number is larger. 求 1 到 10 之间数的和,其逻辑延伸是求用户提供的两个数之间的数的和。可以直接在 for 循环中使用这两个数,使用第一个输入值作为下界而第二个输入值作为上界。然而, 如果用户首先给定的数较大,这种策略将会失败:程序会立即退出 for 循环。因此,我们应该调整范围以便较大的数作上界而较小的数作下界。这样做,我们需要一种方式来判定哪个数更大一些。 Like most languages, C++ provides an if statement that supports conditional execution. We can use an if to write our revised sum program: 像大多数语言一样,C++ 提供支持条件执行的 if 语句。使用 if 语句来编写修订的求和程序如下: #include <iostream> int main() { std::cout << "Enter two numbers:" << std::endl; int v1, v2; std::cin >> v1 >> v2; // read input // use smaller number as lower bound for summation // and larger number as upper bound int lower, upper; if (v1 <= v2) { lower = v1; upper = v2; } else { lower = v2; upper = v1; } int sum = 0; // sum values from lower up to and including upper for (int val = lower; val <= upper; ++val) sum += val; // sum = sum + val std::cout << "Sum of " << lower << " to " << upper << " inclusive is " << sum << std::endl; return 0; } If we compile and execute this program and give it as input the numbers 7 and 3, then the output of our program will be 如果我们编译并执行这个程序给定输入数为 7 和 3,程序的输出结果将为: Sum of 3 to 7 inclusive is 25 Most of the code in this program should already be familiar from our earlier examples. The program starts by writing a prompt to the user and defines four int variables. It then reads from the standard input into v1 and v2. The only new code is the if statement 这个程序中大部分代码我们在之前的举例中已经熟知了。程序首先向用户输出提示并定义 4 个 int 变量,然后从标准输入读入值到 v1 和 v2 中。仅有 if 条件语句是新增加的代码: // use smaller number as lower bound for summation // and larger number as upper bound int lower, upper; if (v1 <= v2) { lower = v1; upper = v2; } else { lower = v2; upper = v1; } The effect of this code is to set upper and lower appropriately. The if condition tests whether v1 is less than or equal to v2. If so, we perform the block that immediately follows the condition. This block contains two statements, each of which does an assignment. The first statement assigns v1 to lower and the second assigns v2 to upper. 这段代码的效果是恰当地设置 upper 和 lower 。if 的条件测试 v1 是否小于或等于 v2。如果是,则执行条件后面紧接着的语句块。这个语句块包含两条语句,每条语句都完成一次赋值,第一条语句将 v1 赋值给 lower ,而第二条语句将 v2 赋值给 upper。 If the condition is falsethat is, if v1 is larger than v2then we execute the statement following the else. Again, this statement is a block consisting of two assignments. We assign v2 to lower and v1 to upper. 如果这个条件为假(也就是说,如果 v1 大于 v2)那么执行 else 后面的语句。这个语句同样是一个由两个赋值语句组成的块,把 v2 赋值给 lower 而把 v1 赋值给 upper 。 Exercise 1.14: | What happens in the program presented in this section if the input values are equal? 如果输入值相等,本节展示的程序将产生什么问题? | Exercise 1.15: | Compile and run the program from this section with two equal values as input. Compare the output to what you predicted in the previous exercise. Explain any discrepancy between what happened and what you predicted. 用两个相等的值作为输入编译并运行本节中的程序。将实际输出与你在上一习题中所做的预测相比较,解释实际结果和你预计的结果间的不相符之处。 | Exercise 1.16: | Write a program to print the larger of two inputs supplied by the user. 编写程序,输出用户输入的两个数中的较大者。 | Exercise 1.17: | Write a program to ask the user to enter a series of numbers. Print a message saying how many of the numbers are negative numbers. 编写程序,要求用户输入一组数。输出信息说明其中有多少个负数。 | | 1.4.4. Reading an Unknown Number of Inputs 1.4.4. 读入未知数目的输入 Another change we might make to our summation program on page 12 would be to allow the user to specify a set of numbers to sum. In this case we can't know how many numbers we'll be asked to add. Instead, we want to keep reading numbers until the program reaches the end of the input. When the input is finished, the program writes the total to the standard output: 对第 1.4.1 节的求和程序稍作改变,还可以允许用户指定一组数求和。这种情况下,我们不知道要对多少个数求和,而是要一直读数直到程序输入结束。输入结束时,程序将总和写到标准输出: #include <iostream> int main() { int sum = 0, value; // read till end-of-file, calculating a running total of all values read while (std::cin >> value) sum += value; // equivalent to sum = sum + value std::cout << "Sum is: " << sum << std::endl; return 0; } If we give this program the input 如果我们给出本程序的输入: 3 4 5 6 then our output will be 那么输出是: Sum is: 18 As usual, we begin by including the necessary headers. The first line inside main defines two int variables, named sum and value. We'lluse value to hold each number we read, which we do inside the condition in the while: 与平常一样,程序首先包含必要的头文件。main 中第一行定义了两个 int 变量,命名为 sum 和 value。在 while 条件中,用 value 保存读入的每一个数: while (std::cin >> value) What happens here is that to evaluate the condition, the input operation 这里所产生的是,为判断条件,先执行输入操作 std::cin >> value is executed, which has the effect of reading the next number from the standard input, storing what was read in value. The input operator (Section 1.2.2, p. 8) returns its left operand. The condition tests that result, meaning it tests std::cin. 它具有从标准输入读取下一个数并且将读入的值保存在 value 中的效果。输入操作符(第 1.2.2 节)返回其左操作数。while 条件测试输入操作符的返回结果,意味着测试 std::cin。 When we use an istream as a condition, the effect is to test the state of the stream. If the stream is validthat is, if it is still possible to read another input then the test succeeds. An istream becomes invalid when we hit end-of-file or encounter an invalid input, such as reading a value that is not an integer. An istream that is in an invalid state will cause the condition to fail. 当我们使用 istream 对象作为条件,结果是测试流的状态。如果流是有效的(也就是说,如果读入下一个输入是可能的)那么测试成功。遇到文件结束符或遇到无效输入时,如读取了一个不是整数的值,则 istream 对象是无效的。处于无效状态的 istream 对象将导致条件失败。 Until we do encounter end-of-file (or some other input error), the test will succeed and we'll execute the body of the while. That body is a single statement that uses the compound assignment operator. This operator adds its right-hand operand into the left hand operand. 在遇到文件结束符(或一些其他输入错误)之前,测试会成功并且执行 while 循环体。循环体是一条使用复合赋值操作符的语句,这个操作符将它的右操作数加到左操作数上。 Operating systems use different values for end-of-file. On Windows systems we enter an end-of-file by typing a control-zsimultaneously type the "ctrl" key and a "z." On UNIX systems, including Mac OS-X machines, it is usually control-d. 操作系统使用不同的值作为文件结束符。Windows 系统下我们通过键入 control—z——同时键入“ctrl”键和“z”键,来输入文件结束符。Unix 系统中,包括 Mac OS—X 机器,通常用 control—d。 | Once the test fails, the while terminates and we fall through and execute the statement following the while. That statement prints sum followed by endl, which prints a newline and flushes the buffer associated with cout. Finally, we execute the return, which as usual returns zero to indicate success. 一旦测试失败,while 终止并退出循环体,执行 while 之后的语句。该语句在输出 sum 后输出 endl,endl 输出换行并刷新与 cout 相关联的缓冲区。最后,执行 return,通常返回零表示程序成功运行完毕。 Exercise 1.18: | Write a program that prompts the user for two numbers and writes each number in the range specified by the two numbers to the standard output. 编写程序,提示用户输入两个数并将这两个数范围内的每个数写到标准输出。 | Exercise 1.19: | What happens if you give the numbers 1000 and 2000 to the program written for the previous exercise? Revise the program so that it never prints more than 10 numbers per line. 如果上题给定数 1000 和 2000,程序将产生什么结果?修改程序,使每一行输出不超过 10 个数。 | Exercise 1.20: | Write a program to sum the numbers in a user-specified range, omitting the if test that sets the upper and lower bounds. Predict what happens if the input is the numbers 7 and 3, in that order. Now run the program giving it the numbers 7 and 3, and see if the results match your expectation. If not, restudy the discussion on the for and while loop until you understand what happened. 编写程序,求用户指定范围内的数的和,省略设置上界和下界的 if 测试。假定输入数是 7 和 3,按照这个顺序,预测程序运行结果。然后按照给定的数是 7 和 3 运行程序,看结果是否与你预测的相符。如果不相符,反复研究关于 for 和 while 循环的讨论直到弄清楚其中的原因。 | | |