Is unsigned char always promoted to int?

后端 未结 2 1673
北荒
北荒 2020-12-11 17:17

Suppose the following:

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

unsigned int shmoo = foo + bar;

Are foo and bar

相关标签:
2条回答
  • 2020-12-11 17:30

    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

    0 讨论(0)
  • 2020-12-11 17:35

    I ran across this yesterday - hope that my answer is on topic.

    uint8_t x =  10;
    uint8_t y = 250;
    
    if (x - y > 0) {
        // never happens
    }
    
    if (x - y < 0U) {
        // always happens
    }
    

    To my eyes at least it was appearing as though values x and y were being unexpectedly promoted, when in fact is was their result that was promoted.

    0 讨论(0)
提交回复
热议问题