gpt4 book ai didi

c++ - 操作 "false < true"是否定义明确?

转载 作者:IT老高 更新时间:2023-10-28 11:30:39 26 4
gpt4 key购买 nike

C++ 规范是否定义:

  1. boolean 参数是否存在“小于”运算符,如果存在,
  2. 4 个参数排列的结果?

换句话说,规范定义了以下操作的结果吗?

false < false
false < true
true < false
true < true

在我的设置 (Centos 7, gcc 4.8.2) 中,下面的代码给出了我的预期(鉴于 C 将 false 表示为 0 并将 true 表示为 1 的历史):

false < false = false
false < true = true
true < false = false
true < true = false

虽然我很确定大多数(所有?)编译器都会给出相同的输出,但这是由 C++ 规范规定的吗?还是允许混淆但符合规范的编译器决定真小于假?

#include <iostream>

const char * s(bool a)
{
return (a ? "true" : "false");
}

void test(bool a, bool b)
{
std::cout << s(a) << " < " << s(b) << " = " << s(a < b) << std::endl;
}

int main(int argc, char* argv[])
{
test(false, false);
test(false, true);
test(true, false);
test(true, true);
return 0;
}

最佳答案

TL;DR:

这些操作根据 C++ 标准草案进行了很好的定义。

详情

我们可以通过转到 draft C++ standard 来查看。 5.9 关系运算符部分说(强调我的 future ):

The operands shall have arithmetic, enumeration, or pointer type, or type std::nullptr_t. The operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) all yield false or true. The type of the result is bool

和 bool 是 3.9.1 基本类型中的算术类型

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types.

Integral and floating types are collectively called arithmetic types.

truefalse 是来自 2.14.6 的 boolean 文字:

boolean-literal:
false
true

回到 5.9 部分,进一步了解关系运算符的机制,它说:

The usual arithmetic conversions are performed on operands of arithmetic or enumeration type.

常用的算术转换5 部分中有介绍,其中说:

Otherwise, the integral promotions (4.5) shall be performed on both operands

4.5 节说:

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

等等表达式:

false < false
false < true
true < false
true < true

使用这些规则变成:

0 < 0
0 < 1
1 < 0
1 < 1

关于c++ - 操作 "false < true"是否定义明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26143976/

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