c++ - C++中按位运算符的结果

标签 c++

测试几个编译器(Comeau、g++)确认某些“整数类型”的按位运算符的结果是一个 int:

void foo( unsigned char );
void foo( unsigned short );

unsigned char a, b;

foo (a | b);

我希望“a | b”的类型是一个无符号字符,因为两个操作数都是无符号字符,但编译器说结果是一个整数,并且对 foo() 的调用是不明确的。为什么语言被设计成结果是一个 int,或者这个实现依赖?

谢谢,

最佳答案

这实际上是标准的 C++ 行为 (ISO/IEC 14882):

5.13/1 Bitwise inclusive OR operator

The usual arithmetic conversions are performed; the result is the bitwise inclusive OR function of its operands. The operator applies only to integral or enumeration operands.

5/9 Usual arithmetic conversions

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions shall be performed on both operands.
  • ...

4.5/1 Integral Promotions

An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.

我认为这与 int 有关,它被认为是执行环境的“自然”大小,以允许高效的算术(参见 Charles Bailey's answer)。

关于c++ - C++中按位运算符的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3357614/

相关文章:

c++ - 外部变量未定义

c++ - 区分 C++ 中的多态类型

C++函数调用,为什么要用析构函数?

c++ - 客户端和服务器示例不工作

C++ 编码逻辑 - 各种想法

c++ - 引入std::enable_if后出现"No match"错误

c++ - 存在 ARM GNU 编译器 -j[jobs] 选项

c++ - 在指针指向一个指针字段的场景中访问值,每个指针都指向 int

c++ - 在 ubuntu 上为 ARM 交叉编译 openCV

c++ - C++ 中的单元测试客户端/服务器应用程序