C++ if条款中的转让无效
考虑以下代码(我意识到这是一种不好的做法,只是好奇为什么会发生这种情况): 因此,显然在第二个if子句中,C++ if条款中的转让无效,c++,if-statement,variable-assignment,C++,If Statement,Variable Assignment,考虑以下代码(我意识到这是一种不好的做法,只是好奇为什么会发生这种情况): 因此,显然在第二个if子句中,output(即0)的赋值实际上没有发生。如果我像这样重新编写代码: #include <iostream> int main() { bool show = false; int output = 3; if (show = output || show) std::cout << output << std:
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;
}
有人能解释一下这里到底发生了什么吗?为什么在第一个示例的第二个if子句中,
output
未指定给show
?我正在Windows 10上使用Visual Studio 2017工具链。由于| |运算符的运算符优先级高于赋值运算符,因此赋值不会发生。将输出| | show赋值为0 | | true,该值在第二个if中计算为true。由于| |运算符的运算符优先级高于赋值运算符,因此赋值不会发生。将输出| | | show赋值为0 | | | true,该值在第二个if中计算为true。这与运算符优先级有关。您的代码:
if (show = output || show)
与
if (show = (output || show))
如果更改顺序,结果将更改:
if ((show = output) || show)
使用类似于上面的if语句,它将打印:
3
show: 1
show: 0
这与运算符优先级有关。您的代码:
if (show = output || show)
与
if (show = (output || show))
如果更改顺序,结果将更改:
if ((show = output) || show)
使用类似于上面的if语句,它将打印:
3
show: 1
show: 0
查找您正在使用的运算符的优先级。您正在执行的是
if(show=(output | | show))
。这就是为什么我假设任何if
语句包含的赋值未正确插入括号的赋值都是错误的。请查找您正在使用的运算符的优先级。您正在执行的是if(show=(output | | show))
。这就是为什么我假设任何包含赋值的if
语句都是错误的。