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

后端 未结 4 1716
情深已故
情深已故 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:38

    The linked question seems to cover it pretty well: the CPU just doesn't. A 32-bit CPU has its native arithmetic operations set up for 32-bit registers. The processor prefers to work in its favorite size, and for operations like this, copying a small value into a native-size register is cheap. (For the x86 architecture, the 32-bit registers are named as if they are extended versions of the 16-bit registers (eax to ax, ebx to bx, etc); see x86 integer instructions).

    For some extremely common operations, particularly vector/float arithmetic, there may be specialized instructions that operate on a different register type or size. For something like a short, padding with (up to) 16 bits of zeroes has very little performance cost and adding specialized instructions is probably not worth the time or space on the die (if you want to get really physical about why; I'm not sure they would take actual space, but it does get way more complex).

提交回复
热议问题