一个条件(C/C++)中的多个表达式
multiple expressions in a condition (C/C++)
在执行控制块之前,我想确保所有3个条件都得到相同的答案:
#include <iostream>
#include <cstdlib>
int main(){
///BUT THIS DOES NOT WORK!
if ( (2 + 2) == (1 + 3) == (4 + 0) ){
std::cout << "not executed" << std::endl;
}
return EXIT_SUCCESS;
}
假设这些数字实际上是变量。这就是我要做的:
#include <iostream>
#include <cstdlib>
int main(){
int n1 = 2;
int n2 = 2;
int n3 = 1;
int n4 = 3;
int n5 = 4;
int n6 = 0;
int a = n1 + n2;
///this works
if ( (n3 + n4) == a && (n5 + n6) == a){
std::cout << "executed!" << std::endl;
}
return EXIT_SUCCESS;
}
问题:为什么我的第一个例子不起作用
我可以为多个变量分配相同的值,如下所示:
#include <iostream>
#include <cstdlib>
int main(){
int a,b,c,d;
a=b=c=d=9;
///prints: 9999
std::cout <<a<<b<<c<<d<<'n';
return EXIT_SUCCESS;
}
希望有人能解释为什么这种评估方法不起作用
最近,我在写一个if语句时注意到了这一点,该语句确定nxn数组是否为幻方。
(2 + 2) == (1 + 3) == (4 + 0)
首先,(2 + 2) == (1 + 3)
计算为true
,因为它确实包含4 == 4
。
然后,您正在比较true == (4 + 0)
。在这种情况下,布尔值被强制转换为整数:
true -> 1
false -> 0
因此,您正在比较1 == 4
,结果为false。
此部分产生布尔值或整数0
或1
:
(2 + 2) == (1 + 3)
因此,表达式的其余部分看起来像:
1 == (4 + 0)
或
0 == (4 + 0)
这两者都不正确。
唯一接受三个参数的运算符是foo ? bar : baz
运算符。其他一切都需要一两个论点。
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 提升精神:解析布尔表达式并简化为规范范式
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用正则表达式regex_search在字符串中查找字符串
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 概念中的cv限定符需要表达式参数列表
- 为什么constexpr的性能比正常表达式差
- 对于结构,表达式必须是可修改的ivalue
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 将fold表达式与std::一起用于两个元组
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- 标记 '","' 之前的预期主表达式
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 带有用户定义类的c++折叠表达式
- 即使使用调试编译标志,表达式也是"optimized out"
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- 这 4 个 lambda 表达式之间有什么区别?