Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unsigned char always promoted to int?

Suppose the following:

unsigned char foo = 3;
unsigned char bar = 5;

unsigned int shmoo = foo + bar;

Are foo and bar values guaranteed to be promoted to int values for the evaluation of the expression foo + bar -- or are implementations allowed to promote them to unsigned int?

In section 6.2.5 paragraph 8:

For any two integer types with the same signedness and different integer conversion rank (see 6.3.1.1), the range of values of the type with smaller integer conversion rank is a subrange of the values of the other type.

In section 6.2.5 paragraph 9:

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

The guarantee that an integer type with smaller integer conversion rank has a range of values that is a subrange of the values of the other type seems dependent on the signedness of the integer type.

  • signed char corresponds to signed int
  • unsigned char corresponds to unsigned int

Does this mean that the value of an unsigned char is only guaranteed to be in the subrange of unsigned int and not necessarily int? If so, does that imply that an implementation could theoretically have an unsigned char value which is not in the subrange of an int?

like image 717
Vilhelm Gray Avatar asked Jul 26 '13 13:07

Vilhelm Gray


1 Answers

are implementations allowed to promote them to unsigned int?

Implementations will promote to unsigned int if not all unsigned char values are representable in an int (as ruled by 6.2.5p9 in C99). See below for implementation examples.

If so, does that imply that an implementation could theoretically have an unsigned char value which is not in the subrange of an int?

Yes, example: DSP cpu with CHAR_BIT 16 or 32.

For example, TI C compiler for TMS320C55x: CHAR_BIT is 16 and UCHAR_MAX 65535, UINT_MAX 65535 but INT_MAX 32767.

http://focus.ti.com/lit/ug/spru281f/spru281f.pdf

like image 69
ouah Avatar answered Sep 25 '22 21:09

ouah