按位移位将无符号字符提升为int [英] bitwise shift promotes unsigned char to int
问题描述
以下代码:
unsigned char result;
result = (result << 4 );
使用gcc版本4.6.4(Debian 4.6.4-2)进行编译,带有-Wconversion标志会导致警告
Compiled with gcc version 4.6.4 (Debian 4.6.4-2), with the -Wconversion flag results in the warning
警告:从'int'转换为'unsigned char'可能会更改其值[-Wconversion]
warning: conversion to 'unsigned char' from 'int' may alter its value [-Wconversion]
那是为什么?
推荐答案
因为该标准如此规定.二进制运算符的操作数
进行整体提升,其中任何小于
int
升级为int
;手术的结果有
还要键入int
.如果说原始价值是
0x12
,结果将是0x120
,并将其分配给
unsigned char
将导致值更改. (分配
值将为0x20
.)发出警告.
Because the standard says so. The operands to binary operators
undergo integral promotion, in which anything smaller than an
int
is promoted to int
; the results of the operation have
type int
as well. And if the original value were, say,
0x12
, the results would be 0x120
, and assigning this to an
unsigned char
will cause a change in value. (The assigned
value will be 0x20
.) Whence the warning.
从标准(第5.8节Shift运算符):
属于整数或无范围枚举类型且为整数
进行促销.结果的类型是
提升为左操作数."与其他二进制运算符不同的是,
no 努力从两个运算符中找到一个通用类型:
结果类型是左操作数句点的类型.但不可或缺
促销确实仍然存在:unsigned char
将是
提升为int
(如果int
的大小为,则提升为unsigned int
1).
From the standard (§5.8 Shift operators): " The operands shall
be of integral or unscoped enumeration type and integral
promotions are performed. The type of the result is that of the
promoted left operand." Unlike other binary operators, there is
no effort to find a common type from the two operators: the
result type is that of the left operand, period. But integral
promotion does still occur: the unsigned char
will be
promoted to int
(or to unsigned int
if int
has a size of
1).
这篇关于按位移位将无符号字符提升为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!