在一个简单项目的工作中,我发现了我不完全理解的情况。考虑以下代码:
#include <iostream>
using namespace std;
bool test(int k)
{
cout << "start " << k << endl;
bool result; // it is important that result's value is opposite to initial value of recheck in main()
result = false;
return result;
}
int main()
{
bool recheck;
recheck = true;
for (int i = 2; i > -1; i--)
{
recheck = (recheck || test(i)); // (1)
cout << i << " ???" <<endl;
}
cout << "----------------------------" << endl;
cout << endl;
recheck = true;
for (int i = 2; i > -1; i--)
{
recheck = (test(i) || recheck); //different order that in (1)
cout << i << "???" <<endl;
}
return 0;
}
for
它从循环返回完全不同的结果:
2 ???
1 ???
0 ???
----------------------------
start 2
2???
start 1
1???
start 0
0???
似乎第一个test(int k)
甚至没有被调用。我怀疑这与||
运营商有关。有人可以解释这种行为吗?