规则:有利于后递增和后递减的预增量和预减量。前缀版本不仅更加高效,你就不太可能遇到奇怪的问题。
int x = 5, y = 5;
cout << x << " " << y << endl;
cout << ++x << " " << --y << endl; // prefix
cout << x << " " << y << endl;
cout << x++ << " " << y-- << endl; // postfix
cout << x << " " << y << endl;
这个程序打印什么值?答案是:它是不确定的。如果+ +被施加到x之前的赋值,答案将是1。如果+ +被施加到x后的赋值,答案将是2。还有其他的情况下,C++并不指定某些东西的计算顺序不同,所以编译器会做出不同的假设。甚至当C++不清楚事情应该怎样评价,一些编译器实现涉及的变量具有副作用的不当行为。这些问题通常都可以避免,以确保任何有一个副作用的变量在一个给定的语句中使用不超过一次。
规则:不要使用一个有副作用的变量在一个给定的语句中不止一次地使用它。
1
2
3
4
5
6
7
8
9
10
11
12
13
int add(int x, int y)
{
return x + y;
}
int main()
{
int x = 5;
int value = add(x, ++x); // is this 5 + 6, or 6 + 6? It depends on what order your compiler evaluates the function arguments in
std::cout << value; // value could be 11 or 12, depending on how the above line evaluates!
return 0;
}
In this example, all we’ve done is change the names of variables a and b inside of main() to x and y. This program still runs fine, even though both main() and add() now have variables named x and y. Why doesn’t this cause a naming conflict? Because x and y in main() have local scope, add() can’t see them. Neither add() nor main() know that the other has variables with the same names!
This helps prevent naming conflicts, because each function doesn’t need to know or care what other functions name their variables. This also prevents functions from being able to inadvertently (or intentionally) change the values of variables inside other functions.
We’ll talk more about local scope, and other kinds of scope, in chapter 4.
Rule: Names used for function parameters or variables declared in a function body are only visible within the function that declares them.