【发布时间】:2019-03-25 22:54:20
【问题描述】:
考虑以下代码(我意识到这是不好的做法,只是想知道它为什么会发生):
#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
谁能解释这里实际发生了什么?为什么在第一个示例的第二个 if 子句中 output 没有分配给 show?我在 Windows 10 上使用 Visual Studio 2017 工具链。
【问题讨论】:
-
查找您正在使用的运算符的优先级。
-
你在做
if (show = (output || show))。 -
这就是为什么我假设任何
if语句包含一个没有正确括号赋值的赋值是错误。
标签: c++ if-statement variable-assignment