Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integral promotion

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?

like image 874
Frank Vilea Avatar asked May 18 '12 23:05

Frank Vilea


1 Answers

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.

like image 88
Ry- Avatar answered Oct 23 '22 06:10

Ry-