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)? 回答1: 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