如果算术运算的结果没有存储在内存中会发生什么
What happens if the result of an arithmetic operation isn't stored in memory
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°
我们的第一个版本是这样的
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;
语句也没有。
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;
,您会看到代码!
如果不使用计算结果(编译器可以证明),那么它将完全消除计算。
至少如果它是一个非垃圾编译器。
未优化的调试版本当然是例外。
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°
我们的第一个版本是这样的
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;
语句也没有。
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;
,您会看到代码!
如果不使用计算结果(编译器可以证明),那么它将完全消除计算。 至少如果它是一个非垃圾编译器。
未优化的调试版本当然是例外。