簡體   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