c++编译器会优化0*x吗?我的意思是,它是转换为0,还是做乘法运算?
谢谢
发布于 2012-07-15 12:56:15
它可能:
int x = 3;
int k = 0 * 3;
std::cout << k;
00291000 mov ecx,dword ptr [__imp_std::cout (29203Ch)]
00291006 push 0
00291008 call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (292038h)]
它甚至完全优化了变量。
但它可能不会:
struct X
{
friend void operator *(int first, const X& second)
{
std::cout << "HaHa! Fooled the optimizer!";
}
};
//...
X x;
0 * x;
发布于 2012-07-15 13:53:18
如果x是一个基本的整数类型,那么代码生成器将使用通常称为“算术规则”的优化来进行如下更改:
int x = ...;
y = 0 * x; ===> y = 0
y = 1 * x; ===> y = x
y = 2 * x; ===> y = x + x;
但仅适用于整型。
如果x是非整数类型,则0 * x
可能并不总是等于0
,或者可能有副作用。
https://stackoverflow.com/questions/11492081
复制