判断的短路规则

所谓的判断short circuiting,是指在条件判断式中,如果前者已经满足了先决条件,就不会执行后置的表达式。例如下面这个程序:

1
2
3
4
5
6
7
int x = 0;
if (false && ++x)
cout << x;
if (true || ++x)
cout << x;
cout << x;
return 0;

屏幕输出为00。这个操作不是编译时处理,而是程序运行时处理的,因此,即便是换成以下程序

1
2
3
4
5
6
7
8
int x;
std::cin >> x;
if (x!=0 && ++x)
std::cout << x;
if (x==0 || ++x)
std::cout << x;
std::cout << x;
return 0;

当输入0时也仍然输出00。判断的实现是基于条件下的跳转,而不是编译器优化。

Ads by Google

Read our privacy policy on how these personalized advertisements are delivered to you.

For your reading experience, we provide full-text RSS feeds. Although math formulas cannot be displayed well, the interface can be adjusted as you like and there are no ads.