Does c++ compiler optimize 0*x? I mean does it convert to 0 or it actually does the multiplication?
Thanks
Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.
Yes, compilers generate the most optimal code for such simplistic calculations.
Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed. I would suggestion starting at the Compiler optimization wikipedia page as there are many different kinds of optimization that are performed at many different stages.
GCC has a range of optimization levels, plus individual options to enable or disable particular optimizations. The overall compiler optimization level is controlled by the command line option -On, where n is the required optimization level, as follows: -O0 . (default).
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;
If x is a primitive integral type than the code generator will use optimizations generally referred to as "Arithmetic Rules" to make changes such as:
int x = ...;
y = 0 * x; ===> y = 0
y = 1 * x; ===> y = x
y = 2 * x; ===> y = x + x;
but only for integral types.
If x is of a non-integral type than 0 * x
might not always be equal to 0
, or may have side-effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With