c ++编译器是否优化0*x?

use*_*260 6 c++ optimization

c ++编译器是否优化0*x?我的意思是它转换为0还是它实际上是乘法?

谢谢

Luc*_*ore 7

它可能:

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)] 
Run Code Online (Sandbox Code Playgroud)

它甚至完全优化了变量.

但它可能不会:

struct X
{
    friend void operator *(int first, const X& second)
    {
       std::cout << "HaHa! Fooled the optimizer!";
    }
};

//...
X x;
0 * x;
Run Code Online (Sandbox Code Playgroud)

  • 此外,对于 IEEE 浮点运算,0*x 并不总是 0。 (2认同)

And*_*zos 6

如果 x 是原始整数类型,则代码生成器将使用通常称为“算术规则”的优化来进行更改,例如:

int x = ...;
y = 0 * x;   ===> y = 0
y = 1 * x;   ===> y = x
y = 2 * x;   ===> y = x + x;
Run Code Online (Sandbox Code Playgroud)

但仅适用于整数类型。

如果 x 是非整数类型,则0 * x可能并不总是等于0,或者可能有副作用。