它是不确定的

在第三行中,x和y是递增/递减之前,他们的评价,所以他们的新值打印由cout。在第五行,一个原始值的临时副本(x = 6,y = 4)发送给cout,然后原来的x和y是递增的。这就是为什么从后缀式操作符的结果没有改变到下一行。

规则:有利于后递增和后递减的预增量和预减量。前缀版本不仅更加高效,你就不太可能遇到奇怪的问题。

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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值