关于括号、布尔逻辑和'n'

About parentheses, boolean logic, and ' '

本文关键字:逻辑和 于括号 布尔      更新时间:2023-10-16

我发现(true&& false(给出0,但true true& amp;false(无括号(给出1。这个问题可能是愚蠢的,因为我刚刚开始学习C ,但是我在任何地方都找不到答案。

我运行以下内容:

cout << (true && false) << 'n';
cout << true && false << 'n';
cout << (true && false == true);

它给了我:

    0    10

看到了这一点,我变得更加困惑:

  1. (true && false)true && false(无括号(有什么区别?
  2. 因为true && false给了我1,所以我认为没有括号的true && falsetrue。但是,(true && false == true)给了我0。为什么?是因为01不一定指示falsetrue
  3. 另外,第二行中的'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