Why must a short be converted to an int before arithmetic operations in C and C++?

后端 未结 4 1628
情深已故
情深已故 2020-11-22 05:25

From the answers I got from this question, it appears that C++ inherited this requirement for conversion of short into int when performing arithmet

4条回答
  •  礼貌的吻别
    2020-11-22 05:44

    short and char types are considered by the standard sort of "storage types" i.e. sub-ranges that you can use to save some space but that are not going to buy you any speed because their size is "unnatural" for the CPU.

    On certain CPUs this is not true but good compilers are smart enough to notice that if you e.g. add a constant to an unsigned char and store the result back in an unsigned char then there's no need to go through the unsigned char -> int conversion. For example with g++ the code generated for the inner loop of

    void incbuf(unsigned char *buf, int size) {
        for (int i=0; i

    is just

    .L3:
        addb    $1, (%rdi,%rax)
        addq    $1, %rax
        cmpl    %eax, %esi
        jg  .L3
    .L1:
    

    where you can see that an unsigned char addition instruction (addb) is used.

    The same happens if you're doing your computations between short ints and storing the result in short ints.

提交回复
热议问题