lve*_*lla 3 c c++ language-lawyer
请考虑以下代码:
int f(int a, int b, int *c) {
*c = a + b;
return *c > 0;
}
void check(int a, int b) {
int c;
if(f(a, b, &c) && c < 10) {
puts("sum is in range [1, 9]");
}
}
Run Code Online (Sandbox Code Playgroud)
如果&&评估了第二部分,是否c保证通过函数调用保存分配给它的值f(a, b, &c)?此行为是否从C更改为C++?
如果出现控制评估顺序的序列点,则是安全的.
// bad: evaluation order of f() and (c < 10) is not specified by C
if(f(a, b, &c) & c < 10) {
// OK, left half of && must occur first.
if(f(a, b, &c) && c < 10) {
Run Code Online (Sandbox Code Playgroud)
使用简单的&&表达式,没有C,C++的区别.使用C/C++评估左侧,如果左侧不是假,则评估右侧.
在C++中,此点上的行为更复杂,&&操作符可能会过载,然后&&始终评估两端.