Integral promotion

纵然是瞬间 提交于 2019-11-28 01:05:41

问题


When is it ever the case that a signed integer cannot represent all the values of the original type with regards to integer promotion?

From the text K&R, C Programming Language, 2nd Ed. p. 174

A.6.1 Integral Promotion

A character, a short integer, or an integer bit-field, all either signed or not, or an object of enumeration type, may be used in an expression wherever an integer may be used. If an int can represent all the values of the original type, then the value is converted to int; otherwise the value is converted to unsigned int. This process is called integral promotion.

This code shows the limits of the types for my system:

#include <stdio.h>
#include <limits.h>

int main(void)
{

    printf("CHAR_MAX: %i\n", CHAR_MAX);     
    printf("UCHAR_MAX: %i\n", UCHAR_MAX);

    printf("SHORT_MAX: %i\n", SHRT_MAX);        
    printf("USHORT_MAX: %i\n", USHRT_MAX);

    printf("INT_MAX: %i\n", INT_MAX);       
    printf("UINT_MAX: %u\n", UINT_MAX);

    return 0;
}

The result is:

CHAR_MAX: 127
UCHAR_MAX: 255
SHORT_MAX: 32767
USHORT_MAX: 65535
INT_MAX: 2147483647
UINT_MAX: 4294967295

The signed int type is way bigger than any of the other types, so when would it ever fall back to UINT_MAX?


回答1:


It's possible for a short int to be the same size as an int, so an unsigned short int could not be promoted to an int, for example. This just isn't the case on your compiler.



来源:https://stackoverflow.com/questions/10660758/integral-promotion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!