Daniel Daniel - 2 months ago 9
C++ Question

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

Answer

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

Comments