簡體   English   中英

C++ 中 if 的奇怪行為

[英]Strange behaviour of if in C++

在我的工作中,我嘗試使用這種結構:

if (repl && (repl = replaced.count(*l))) {
    // repl isn't used here 
    ...
}

在我看來,它的工作方式應該與

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

因為&&中的表達式從左到右計算,但出乎意料的是它不是。
它是 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;
    }
}

output:

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;
}

output:奇怪

&&短路。 您的原始代碼等效於:

if (repl) {
   repl = replaced.count(*l))
   if (repl) {
    // repl isn't used here 
    ...
  }
}

除了@Sebastian Redl 的答案也是一個很好的答案之外,我想澄清這個概念。 以下代碼將有助於理解short-circuiting的概念。

#include <iostream>

bool printret(bool ret){
    std::cout << "printret call: " << ret << std::endl;
    return ret;
}


int main()
{
    std::cout << "first test :" << std::endl;
    if(printret(true) && printret(false)){}

    std::cout << "second test:" << std::endl;
    if(printret(false) && printret(true)){}
    return 0;
}

Output:

first test :
printret call: 1
printret call: 0
second test:
printret call: 0

第二個測試實際上忽略了&&右側的表達式,因為第一個表達式(在&&的左側)返回 false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM