奇怪的GCC短整型转换警告 [英] Strange GCC short int conversion warning
问题描述
我有位C code,肚里酷似这样的:
I have a bit of C code, which goes exactly like this:
short int fun16(void){
short int a = 2;
short int b = 2;
return a+b;
}
当我试着使用GCC编译它,我得到警告:
When I try to compile it with GCC, I get the warning:
warning: conversion to 'short int' from 'int' may alter its value [-Wconversion]
return a+b;
^
虽然没有明显的转化。两个操作数很短,即使返回值是短为好。那么,有什么收获?
Though there is no visible conversion. Both operands are short and even the returning value is short as well. So, what's the catch?
推荐答案
在做算术运算,操作数是受通常的算术转换(中的Acme's回答 - 他打我,但我会继续和张贴反正:-))。这些扩大短整型
纯 INT
,所以:
When you do arithmetic computations, the operands are subject to "the usual arithmetic conversions" (a superset of the "integer promotions" quoted in Acme's answer—he beat me to this but I'll go ahead and post anyway :-) ). These widen short int
to plain int
, so:
a + b
计算相同的结果为:
computes the same result as:
((int) a) + ((int) b)
的收益
语句则必须将此 INT
范围缩小到短整型
,而这正是GCC产生的警告。
The return
statement must then narrow this int
to a short int
, and this is where gcc produces the warning.
这篇关于奇怪的GCC短整型转换警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!