Microsoft C++ 编译器有错误? [英] Microsoft C++ compiler have a bug?

查看:36
本文介绍了Microsoft C++ 编译器有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用了 int x=1;有符号 int y = -1;双 z = y * x * 0.25;

我使用的是 Microsoft Visual Studio 10 C++ 编译器.为什么 z 没有 -0.25 值?正如我从反汇编中看到的那样,它生成一个有符号整数乘法 (imul),将 edx 的结果放在堆栈上,并用 0! 扩展它,因为它将是一个无符号整数.之后,它使用 FP 指令将其相乘.

<预><代码>........imul edx,dword ptr [ecx]mov dword ptr [ebp-98h],edxmov dword ptr [ebp-94h],0fild dword ptr [ebp-98h]fmul qword ptr [__real@3fd0000000000000 (1402FB8h)]fstp qword ptr [z]

为什么有符号*无符号相乘的结果被解释为无符号?

解决方案

表达式 y * x * 0.25 在两个 C 中都关联为 (y * x) * 0.25和 C++.

当一个unsigned int和一个signed int相乘时,两个操作数都被转换为unsigned int,结果也是一个unsigned int 由于 C 和 C++ 中算术表达式的整数转换规则,所以 y * x 的结果在 C 和 C 中都是 UINT_MAX - 1C++.

无论您是将示例编译为 C 还是 C++,您的示例都不会出现编译器错误.

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.25 associates as (y * x) * 0.25 in both C and C++.

When multiplying an unsigned int and a signed int, both operands are converted to unsigned int and the results is also an unsigned int due to the integer conversion rules for arithmetic expressions in both C and C++ so the result of y * x will be UINT_MAX - 1 in both C and C++.

Your example doesn't exhibit a compiler bug whether you are compiling your example as C or C++.

这篇关于Microsoft C++ 编译器有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆