繁体   English   中英

如果算术运算的结果未存储在存储器中会发生什么

[英]What happens if the result of an arithmetic operation isn't stored in memory

当我5年前学习C ++时,我们的任务之一就是

创建一个程序,使用公式C°x 9/5 + 32 = F° ,根据摄氏度输入计算华氏温度

我们的第一个版本是这样的

int main()
{
    float celsius;
    cout << "Enter Celsius temperature: ";
    cin >> celsius;
    cout << "Fahrenheit: " << celsius * (9.0 / 5) + 32 << endl;
    return 0;
}

一位同学指出,我们没有明确告知输出结果,结果导致了

int main()
{
    float celsius;
    cout << "Enter Celsius temperature: ";
    cin >> celsius;
    celsius * (9.0 / 5) + 32;
    return 0;
}

我用它作为一个轶事: 在指定要求时总是要彻底

最近我一直在想这个代码是否确实满足了要求。

不是celsius * (9.0 / 5) + 32; 在死代码消除期间,编译器会排除部分内容吗? 代码是在Visual Studio 2010中编译的,没有任何特定的编译器选项。

查看Visual Studio反汇编声明似乎没有生成任何代码,但是再一次, float celsius;也没有float celsius; 声明。

C ++代码和相应的反汇编

     7:     float celsius;
     8:     cout << "Enter Celsius temperature: ";
 push        offset string "Enter Celsius temperature: " (01368B30h)  
 mov         eax,dword ptr [_imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A (0136C098h)]  
 push        eax  
 call        std::operator<<<std::char_traits<char> > (01361370h)  
 add         esp,8  
     9:     cin >> celsius;
 mov         esi,esp  
 lea         eax,[celsius]  
 push        eax  
 mov         ecx,dword ptr [_imp_?cin@std@@3V?$basic_istream@DU?$char_traits@D@std@@@1@A (0136C09Ch)]  
 call        dword ptr [__imp_std::basic_istream<char,std::char_traits<char> >::operator>> (0136C0A0h)]  
 cmp         esi,esp  
 call        __RTC_CheckEsp (0136114Fh)  
    10:     celsius * (9.0 / 5) + 32;
    11:     return 0;
 xor         eax,eax  

是的,看起来编译器优化了该语句。 我打赌如果你使用volatile float celsius; 你会看到代码!

如果没有使用计算结果(并且编译器可以证明这一点),那么它将完全消除计算。 至少如果它是一个非垃圾编译器。

未经优化的调试版本当然是例外。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM