c++type-conversionintegershort

Are there any examples of architectures in which int cannot represent all values of unsigned short despite latter being shorter?


Are there any known examples of architectures out there in which unsigned short is smaller than int yet still only representable by unsigned int after conversion?


Solution

  • No sane compiler would make this possible(1).

    If int is even one bit wider than short, it can represent all values of short and unsigned short. For example:

    See also [basic.fundamental] p3.

    You're probably asking because of the promotion rules to int/unsigned int from narrower types. If int and short have the same amount of bits, then unsigned short gets promoted to unsigned int. 16-bit architectures typically have a 16-bit int and 16-bit short.


    (1) Technically, it's possible that int is larger (in terms of sizeof) than unsigned short but not any wider (in terms of what values it can represent) because integers are allowed to have padding bits. However, it would be utterly nonsensical for int to be larger despite not being wider, so no sane compiler would do this.

    (2) Prior to C++20, the guaranteed lower bound for 17-bit int would only be -216+1.