usigned int x=1;
signed int y = -1;
double z = y * x * 0.25;
I’m using Microsoft Visual Studio 10 C++ compiler.
Why z don’t have -0.25 value?
As I saw from disassembly, it makes an signed int multiply (imul), places the result from edx on the stack, and extends it with 0!, as it would be an unsigned int. After that it multiplies it using FP instructions.
.............
imul edx,dword ptr [ecx]
mov dword ptr [ebp-98h],edx
mov dword ptr [ebp-94h],0
fild dword ptr [ebp-98h]
fmul qword ptr [__real@3fd0000000000000 (1402FB8h)]
fstp qword ptr [z]
Why the result of multiply of signed * unsigned is interpreted as unsigned?
The expression
y * x * 0.25associates as(y * x) * 0.25in both C and C++.When multiplying an
unsigned intand asigned int, both operands are converted tounsigned intand the results is also anunsigned intdue to the integer conversion rules for arithmetic expressions in both C and C++ so the result ofy * xwill beUINT_MAX - 1in both C and C++.Your example doesn’t exhibit a compiler bug whether you are compiling your example as C or C++.