Does c++ compiler optimize 0*x? I mean does it convert to 0 or it actually does the multiplication?
Thanks
Does c++ compiler optimize 0*x? I mean does it convert to 0 or it actually does the multiplication?
Thanks
It might:
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)]
It even optimizes away the variables altogether.
But it might not:
struct X
{
friend void operator *(int first, const X& second)
{
std::cout << "HaHa! Fooled the optimizer!";
}
};
//...
X x;
0 * x;
如果 x 是原始整数类型,则代码生成器将使用通常称为“算术规则”的优化来进行更改,例如:
int x = ...;
y = 0 * x; ===> y = 0
y = 1 * x; ===> y = x
y = 2 * x; ===> y = x + x;
但仅适用于整数类型。
如果 x 是非整数类型,则0 * x
可能并不总是等于0
,或者可能有副作用。