Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do modern compilers optimize multiplication by 1 and -1

If I write

template<int sign>
inline int add_sign(int x) {
    return sign * x;
}

template int add_sign<-1>(int x);
template int add_sign<1>(int x);

Are most C++ compilers smart enough to optimize the multiplication by 1 or -1 into some faster operation (no-op or negation)?

like image 901
dspyz Avatar asked Oct 29 '25 22:10

dspyz


2 Answers

Yes. This is part of a class of simple optimizations known as arithmetic local optimizations. For example 1 * x can be simplified statically to x, likewise -1 * x can be simplified to -x. Production compilers all do this and far more complex optimizations as well.

like image 58
Andrew Tomazos Avatar answered Nov 01 '25 11:11

Andrew Tomazos


For g++, use g++ -S Foo.cc to view the assembler and determine whether the template has been optimized or not. For clang, take a look at this question. For Visual Studio, take a look at this question.

like image 40
merlin2011 Avatar answered Nov 01 '25 11:11

merlin2011



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!