10306:短路求值与副作用
题目
举例说明 && 和 || 的短路求值会影响副作用是否发生。
解析
left && right 先求 left;若其为假,结果已经确定,right 不求值。left || right 也先求 left;若其为真,right 不求值。
解析
c
#include <stdbool.h>
#include <stdio.h>
static int hits;
static bool mark_true(void) {
++hits;
return true;
}
int main(void) {
bool first = false && mark_true();
bool second = true || mark_true();
bool third = true && mark_true();
bool fourth = false || mark_true();
printf(
"%d %d %d %d; hits=%d\n",
first,
second,
third,
fourth,
hits
);
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
输出:
text
0 1 1 1; hits=21