简体   繁体   中英

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

When I was studying C++ 5 years ago, one of our assignments was

Create a program that calculates the temperature in fahrenheit based on the celsius input using the formula C° x 9/5 + 32 = F°

Our first version was something like this

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

A classmates pointed out that we weren't explicitly told to output the result, which resulted in

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

I've used this as an anecdote: always be thorough when specifying requirements

Lately I've been wondering if this code actually did satisfy the requirements.

Wouldn't the celsius * (9.0 / 5) + 32; part be excluded by the compiler during the Dead Code Elimination? The code was compiled in Visual Studio 2010 without any specific compiler options.

Viewing the Visual Studio Disassembly the statement doesn't seem to generate any code, but then again, neither does the float celsius; statement.

C++ code and corresponding Disassembly

     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  

Yes, looks like the compiler optimized the statement away. I bet if you used volatile float celsius; you would see the code!

If the result of a calculation is not used (and the compiler can prove this), then it will eliminate the calculation entirely. At least if it's a non-crap compiler.

Unoptimized debug builds are of course the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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