gpt4 book ai didi

c++ - C++中的值比较结果

转载 作者:行者123 更新时间:2023-12-02 09:47:49 31 4
gpt4 key购买 nike

在下面的代码中,输出为1,但我不确定为什么。我是否已隐式更改为 bool(boolean) 值?如何将整数值设置为这样的表达式?

#include <iostream>
using namespace std;

int main (int argc, const char *argv[])
{
int a = 1, b = 1, c = 1, i = 1;
i = b < a < c;
cout << i;
return 0;
}

最佳答案

Has i been implicitly changed to a boolean?


不会。相反, bool(boolean) 表达式已隐式转换为 int,然后存储在 i中,如@WhozCraig所评论。

How can an integer value be set to an expression like this?


因为它遵循C++标准。

当您这样做时:
i = b < a < c;
由于第一个 <和第二个 <具有相同的运算符优先级(因为它们是相同的运算符),因此:

Operators that have the same precedence are bound to their argumentsin the direction of their associativity. For example, the expression a= b = c is parsed as a = (b = c), and not as (a = b) = c because of right-to-left associativity of assignment, but a + b - c is parsed (a > + b) - c and not a + (b - c) because of left-to-right associativity of addition and subtraction.


C++ Operator Precedence中所述,这意味着将解析您的表达式,就像它是这样写的:
i = (b < a) < c;
这将评估括号内的条件,即False。
现在 boolint的转换是隐式的:
C++标准的第4.7 / 4节说(整体转换)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


这意味着将false转换为0,然后我们基本上完成了:
i = 0 < c;
由于 c等于1,其结果为true。现在 i的类型为 int,这意味着发生了另一次第二次从 bool(boolean) 值到整数的隐式转换,最终将1分配给 i

关于c++ - C++中的值比较结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63865602/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com