c++ - if 子句中的赋值无效
问题描述
考虑以下代码(我意识到这是不好的做法,只是想知道它为什么会发生):
#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 (show = (output || show))
如果更改顺序,结果会更改:
if ((show = output) || show)
使用上面的 if 语句,它会打印:
3
show: 1
show: 0
推荐阅读
- json - 如何将数据保存到 mockapi 服务?
- angular6 - 当我在另一个单元格中选择一个值时如何更改单元格的值
- r - 在 R Studio 中将默认工作目录设置为项目文件夹
- google-bigquery - 我可以一次替换 BigQuery 分区表的分区间隔吗?
- highcharts - Highcharts 中的事件导出数据
- c# - 如何在 sql server 中输入工单的详细信息?
- javascript - 旧 IE 的 Map.set() polyfill?
- mysql - Mysql:获取第一次登录和最后一次注销时间
- c - 架构 x86_64 的未定义符号:“_read_line”,引用自:_insert in inventory-82371b.o
- siege - 为什么“成功的交易”+“失败的交易”!=“交易”