4 ms·
The size of the cpu registers don't matter here. What matters is that 'int' is a bigger type than uint8_t and smaller than uint64_t: the resulting unexpected be
by pm215 9y ago
The size of the cpu registers don't matter here. What matters is that 'int' is a bigger type than uint8_t and smaller than uint64_t: the resulting unexpected behaviour is mandated by the C standard regardless of the register size of the cpu (for instance both 32-bit i386 and 64-bit x86_64 will behave the same, because both typically have 32 bit 'int').
More generally, reasoning about this kind of thing by thinking about the CPU leads you down the wrong path -- modern C as implemented by compilers today is an implementation of a standardized language, and they behave as that standard says, which is not always as you might expect from the hardware behaviour. (Simple example: left shifting of negative numbers does a simple straightforward thing on practically all hardware, but the C spec says it's UB and if you write code that assumes the h/w behaviour you'll get bitten.)
- baby 9y agoEven if the code would still be bad for 32-bit machines, I'm not sure they would suffer from the bug (if they had 32-bit signed int as well). 1. Your uint8_t would get promoted to a 32-bit int 2. Your int would get shifted, getting a 1 in the signing bit 3. The result would get stored in a uint32_t when being casted Now I don't know how uint64_t works on a 32-bit machine, I'd have to compile the C code with -m32 to see. EDIT: just tested and you're right, it's still a problem on 32-bit machines.