C語言允許兩個不同整數(shù)類型的變量现拒,如char
類型變量與int
類型變量相加辣垒。C語言標(biāo)準(zhǔn)稱之為整型提升。那么我們?nèi)绾瓮ㄟ^測試代碼知道一個表達式的類型呢印蔬?
方法1:通過泛型選擇表達式
泛型選擇表達式是C11引入的新特性勋桶,主要用于標(biāo)準(zhǔn)庫,特別是數(shù)學(xué)庫來實現(xiàn)輕量級的泛化處理。言歸正傳例驹,我們來看看如何通過泛化來得到表達式的類型捐韩。代碼如下:
#define GET_TYPE(expr) \
_Generic(expr, double: "double", float: "float", \
signed char: "schar", unsigned char: "uchar", \
int:"int", unsigned int: "uint",\
long: "long", unsigned long: "ulong", \
default: "unknown")
void test(void)
{
char c = 100;
printf("type of c+1 is %s\n", GET_TYPE(c+1));
}
用gcc 6.2.0編譯(-std
設(shè)置為c11
),輸出如下:
type of c+1 is int
這個方法不是十全十美鹃锈。再看一個例子:
float f = 1.1;
printf("type of f+1 is %s\n", GET_TYPE(f+1));
輸出是:
type of f+1 is float
很遺憾荤胁,float
的算術(shù)運算會提升到double
。所以上面的答案不對屎债。
方法2:用gcc的format檢查
這個方法更簡單仅政,甚至都不需要運行代碼,只需要看編譯告警盆驹。
代碼如下:
char c = 100;
printf("%s\n", (c+1));
用gcc編譯(打開編譯開關(guān)-Wformat
或者-Wall
)圆丹,有如下編譯告警:
警告:格式 ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
從中可以得知c+1
的類型是int
。再看看f+1
的類型是啥躯喇?
float f = 1.1;
printf("%s\n", (f+1));
編譯告警如下:
警告:格式 ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘double’ [-Wformat=]
這次對了辫封。