关于括号、布尔逻辑和'n'
About parentheses, boolean logic, and ' '
我发现(true&& false(给出0,但true true& amp;false(无括号(给出1。这个问题可能是愚蠢的,因为我刚刚开始学习C ,但是我在任何地方都找不到答案。
我运行以下内容:
cout << (true && false) << 'n';
cout << true && false << 'n';
cout << (true && false == true);
它给了我:
0 10
看到了这一点,我变得更加困惑:
-
(true && false)
和true && false
(无括号(有什么区别? - 因为
true && false
给了我1
,所以我认为没有括号的true && false
是true
。但是,(true && false == true)
给了我0
。为什么?是因为0
和1
不一定指示false
和true
? - 另外,第二行中的
'n'
似乎不起作用。为什么?
,如操作员优先桌上所示,<<
具有优先级,&&
具有优先级14
结果,表达式 cout << true && false << 'n';
可以重新编写为:
(cout << true) && (false << 'n');
这将评估为:
(cout << true) // Output: "1"; Evaluates to an ostream-object.
(false << 'n') // No output; Evaluates to 0, the 'n' "disappears"
[ostream-object] && 0; // No output; Evaluates to 0
&&
的优先级低于 <<
和 ==
,因此代码的行为为:
cout << (true && false) << 'n';
(cout << true) && (false << 'n');
cout << (true && (false == true));
在第一行,您是真实和错误的。在第二行中,您是正确流的,并移动false the Newline的ASCII值留下(无效(。在第三行中,您正在测试假,如果false等于true,这会产生false。
cout << true && false << 'n';
与
相同 (cout << true) && (false << 'n');
true
(1(流到cout
,返回对流的引用。
&&
false
(0(留下Bitshifted n
(10(位,导致0。
该流现在处于布尔上下文中(由于&&
(,并且将通过其转换操作员operator bool ()
为true
,因为它仍然处于良好状态。
我们剩下的true && 0
,导致false
。
(cout << true) && (false << 'n') ==
(cout << true) && (false << 10) == // right side: 0 << 10
(cout << true) && 0 => // true is sent out here
bool(cout) && 0 =>
true && 0
false
相关文章:
- 检查由括号、方括号和大括号组成的一组方括号是否有效?
- make_pair和大括号 { } 之间的区别,用于在C++中分配一对?
- 为什么带有逻辑和运算符以及增量运算符的 c++ 程序给出的输出与预期不同?
- 如何在.pro文件中为TARGET使用空格和尖括号
- 否则如果和大括号
- 没有数据成员和大括号语法的类的默认复制构造函数
- 构造对象时 c++ 中的括号和大括号有什么区别
- 关于括号、布尔逻辑和'n'
- 双指针 (int**) 和双括号,用于从 2D 数组中获取值
- 带有和没有括号的C 代码的区别是什么?
- 使用逻辑和/或无条件/分支
- 实现简单的逻辑和延迟模拟器
- 验证打开和关闭括号的数量
- 如何使用常见的C 业务逻辑和数据访问层构建跨平台移动应用程序
- 自逻辑和
- 如何使用逻辑和 c++
- 在Qt小部件中分离应用程序逻辑和视图
- C++逻辑&&和||运营商
- 条件操作和大括号会影响代码吗?
- 此指针和 suqare 括号过载