Does the C ++ compiler optimize 0 * x?

Does the C ++ compiler optimize 0 * x? I mean, does this convert to 0 or is it actually doing multiplication?

thanks

+6
source share
2 answers

He can:

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 completely eliminates variables.

But this may not be the case:

 struct X { friend void operator *(int first, const X& second) { std::cout << "HaHa! Fooled the optimizer!"; } }; //... X x; 0 * x; 
+7
source

If x is a primitive integral type, and the code generator will use optimizations, commonly called "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-integer type than 0 * x may not always be 0 or may have side effects.

+4
source

Source: https://habr.com/ru/post/920519/


All Articles