问题描述
以下代码:
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 operatorsundergo integral promotion, in which anything smaller than anint
is promoted to int
; the results of the operation havetype int
as well. And if the original value were, say,0x12
, the results would be 0x120
, and assigning this to anunsigned char
will cause a change in value. (The assignedvalue 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 shallbe of integral or unscoped enumeration type and integralpromotions are performed. The type of the result is that of thepromoted left operand." Unlike other binary operators, there isno effort to find a common type from the two operators: theresult type is that of the left operand, period. But integralpromotion does still occur: the unsigned char
will bepromoted to int
(or to unsigned int
if int
has a size of1).
这篇关于按位移位将无符号字符提升为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!