Search code examples
cinttype-conversionexpressionunsigned-integer

"if an int can hold all values of the original type then the value is converted to int , else to unsigned int"--What it means?


The above line is about implicit integral promotions/conversions in C, taken from the book by Mike Banahan Section 2.8.1.1 (Link). Here's what the exact paragraph is:

No arithmetic is done by C at a precision shorter than int, so these conversions are implied almost whenever you use one of the objects listed below in an expression. The conversion is defined as follows:

Whenever a short or a char (or a bitfield or enumeration type which we haven't met yet) has the integral promotions applied

  • if an int can hold all of the values of the original type then the value is converted to int
  • otherwise, the conversion will be to unsigned int

Here are my confusions about the part in bold. Please clear these:

  • Isn't the "otherwise" part redundant? Shouldn't all short or char types fit into an int by default given that int is larger than either in size? How does the question of a short not fitting into an int and requiring an unsigned int even arise?
  • How is the "otherwise" part valid–If a negative short integer is converted implicitly to unsigned int, won't its value change?

Though I was tempted to dismiss it as trivial and move on, I felt getting a proper explanation would be better. Thank you.


Solution

  • An int type (according to the C standard) does not have to be larger than a short. An int must only "not be shorter" than a short. They could both be 16 bits, for example. In that case, it is possible to have an unsigned short value that cannot fit into an int.

    (The Wikipedia page on C data types is pretty revealing.)