在我的作業中,我嘗試使用這種結構:
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;
}
}
輸出:
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;
}
輸出:奇怪
uj5u.com熱心網友回復:
&&是短路。您的原始代碼等效于:
if (repl) {
repl = replaced.count(*l))
if (repl) {
// repl isn't used here
...
}
}
uj5u.com熱心網友回復:
除了@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;
}
輸出 :
first test :
printret call: 1
printret call: 0
second test:
printret call: 0
第二個測驗實際上忽略了右側的運算式,&&因為第一個運算式(在 的左側&&)回傳 false。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369992.html
