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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With