测试几个编译器(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 tolong double
.- Otherwise, if either operand is
double
, the other shall be converted todouble
.- Otherwise, if either operand is
float
, the other shall be converted tofloat
.- 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
, orunsigned short int
can be converted to an rvalue of typeint
ifint
can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of typeunsigned int
.
我认为这与 int
有关,它被认为是执行环境的“自然”大小,以允许高效的算术(参见 Charles Bailey's answer)。
关于c++ - C++中按位运算符的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3357614/