考虑以下代码(我意识到这是不好的做法,只是想知道为什么会这样):
#include <iostream>
int main() {
bool show = false;
int output = 3;
if (show = output || show)
std::cout << output << std::endl;
std::cout << "show: " << show << std::endl;
output = 0;
if (show = output || show)
std::cout << output << std::endl;
std::cout << "show: " << show << std::endl;
return 0;
}
这打印
3
show: 1
0
show: 1
因此,显然在第二个 if 子句中,output
的赋值,即 0
,实际上并没有发生。如果我像这样重写代码:
#include <iostream>
int main() {
bool show = false;
int output = 3;
if (show = output || show)
std::cout << output << std::endl;
std::cout << "show: " << show << std::endl;
output = 0;
if (show = output) // no more || show
std::cout << output << std::endl;
std::cout << "show: " << show << std::endl;
return 0;
}
如我所料,它输出:
3
show: 1
show: 0
谁能解释一下这里到底发生了什么?为什么 output
没有分配给第一个示例的第二个 if 子句中的 show
?我在 Windows 10 上使用 Visual Studio 2017 工具链。
最佳答案
这与运算符优先级有关。您的代码:
if (show = output || show)
与
相同if (show = (output || show))
如果你改变顺序,结果也会改变:
if ((show = output) || show)
使用上面的 if 语句,它会打印:
3
show: 1
show: 0
关于c++ - if 子句中的赋值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919618/