C++ 中 if 的奇怪行为

0 c++ if-statement

在我的工作中,我尝试使用这种结构:

if (repl && (repl = replaced.count(*l))) {
    // repl isn't used here 
    ...
}
Run Code Online (Sandbox Code Playgroud)

在我看来它的工作方式应该与

bool newRepl = replaced.count(*l);
if (repl && newRepl) {
    // repl isn't used here 
    ...
}
repl = newRepl;
Run Code Online (Sandbox Code Playgroud)

因为 中的表达式是&&从左到右求值的,但出乎意料的是它不是。
它是 C++ 中未指定的构造还是我没有正确理解它应该如何工作?

有问题的代码示例:

std::set<int> set{3, 4, 6};
bool repl = false;
for (size_t i = 3; i < 7; ++i) {
    if (repl && (repl = set.count(i))) {
        std::cout << "strangeif" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

std::set<int> set{3, 4, 6};
bool repl = false;
for (size_t i = 3; i < 7; ++i) {
    bool newRepl = set.count(i);
    if (repl && newRepl) {
        std::cout << "strangeif" << std::endl;
    }
    repl = newRepl;
}
Run Code Online (Sandbox Code Playgroud)

输出:奇怪的

Seb*_*edl 8

&&是短路。您的原始代码相当于:

if (repl) {
   repl = replaced.count(*l))
   if (repl) {
    // repl isn't used here 
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)