OR operator doesn't evaluate both statements, only 1

孤人 提交于 2020-01-17 13:41:47

问题


std::ifstream file_1(argv[1]);
std::ifstream file_2(argv[2]);
...
std::string dummy_1;
std::string dummy_2;
...
while(std::getline(file_1, dummy_1) || std::getline(file_2, dummy_2)) // the problem
{
  ...
}

The condition behaves like the OR operator is evaluating the option on the right only if the file on the left reach the end (returning a FALSE) and it doesn't evaluate them at the same time.

I know that the evaluation of a statement has nothing to do with the operator itself or with its own precedence rules, but my program it's not supposed to work like I'm imaging with both statements being evaluated at the same time ?


回答1:


The OR operator is a short circuit operator, meaning that if one side evaluates to true the other side is never actually executed. If your intention is to have both sides of the OR evaluated then you might want to reconsider how your code is written.




回答2:


That's how boolean OR operates in most programming languages; this behavior is called short-circuit evaluation.

If you want to always evaluate both expressions, do so individually and then use the results inside the conditional:

std::getline(file_1, dummy_1);
std::getline(file_2, dummy_2);
if (file_1 || file_2) { ... }



回答3:


This is called short circuiting. Please check the C FAQ.




回答4:


You can use bitwise logical operator '|' to guarantee the execution of both expressions. But even then, the execution order is not defined in C or C++. (Java would execute from left to right).

if (readline(this_line) | readline(that_line) ) ...
which ever line is read first, is arbitrary.



来源:https://stackoverflow.com/questions/13343387/or-operator-doesnt-evaluate-both-statements-only-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!