Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does c++ compiler optimize 0*x?

Does c++ compiler optimize 0*x? I mean does it convert to 0 or it actually does the multiplication?

Thanks

like image 800
user1509260 Avatar asked Jul 15 '12 12:07

user1509260


People also ask

What is compiler optimization in C?

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.

Do compilers optimize division by 2?

Yes, compilers generate the most optimal code for such simplistic calculations.

Do compilers Optimise code?

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.

Does GCC optimize by default?

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).


2 Answers

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;
like image 51
Luchian Grigore Avatar answered Sep 23 '22 15:09

Luchian Grigore


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.

like image 39
Andrew Tomazos Avatar answered Sep 23 '22 15:09

Andrew Tomazos