[英]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 当我5年前学习C ++时,我们的任务之一就是
Create a program that calculates the temperature in fahrenheit based on the celsius input using the formula C° x 9/5 + 32 = F°
创建一个程序,使用公式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;
不是
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.
代码是在Visual Studio 2010中编译的,没有任何特定的编译器选项。
Viewing the Visual Studio Disassembly the statement doesn't seem to generate any code, but then again, neither does the float celsius;
查看Visual Studio反汇编声明似乎没有生成任何代码,但是再一次,
float celsius;
也没有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;
我打赌如果你使用
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. 未经优化的调试版本当然是例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.