Is constant integer division optimized out by the compiler?
First I feel I must defend myself. I know I should probably not worry about this kind of thing, premature optimization and what-not. I know. I am asking this purely because I'm curious and couldn't (or don't know how) find the solution myself.
Is it common practice for compilers to optimze away constant integer division? Something like this:
const int FOUR = 4;
const int TWO = 2;
int result = FOUR / TWO;
Optimized to be:
const int FOUR = 4;
const int TWO = 2;
int result = 2;
Edit: I'm very much aware that the answer varies from compiler to co开发者_如何学JAVAmpiler, I'm mostly curious if its common practice.
Yes it is virtually universal practice, in fact if your compiler doesn't do it you have a very unusual compiler indeed.
More than common, it's practically required by the language. If you declare result const, it is an integral constant expression, which can be used for things like the dimension of an array. So the compiler has to know the numerical value. This is one "optimization" which occurs even in builds where optimization is turned off.
Yes, it's common when optimization is turned on, however it will depend on the compiler. Visual C++ 9 does this.
If you really care you should inspect the emitted assembly - that's the only reliable way to know.
I'll add that, while for integers it's OK to do "constant folding", there could be problems to do it with floats, so it's not always done for/with them.
For example
http://www.nullstone.com/htmls/category/consfold.htm
Some environments support several floating-point rounding modes that can be changed dynamically at run time. In these environments, expressions such as (1.0 / 3.0) must be evaluated at run-time if the rounding mode is not known at compile time.
Yes but, consider:
void f(int x)
{
return x*3/4
}
order of operations means 3/4 wont be reduced by the compiler
I've compiled and debugged code very similar to yours, and from my experience, I'd say yes. But, that may change compiler-to-compiler (I mostly stick with MSC8-MSC10).
This is referred to as "constant folding" in compiler speak, and it is common on modern compilers. It is not just division that can be optimized; many types of constant expressions can be reduced to a single compile-time constant.
While the answer is "yes" for any popular compiler, I advise you to examine the disassembly of your code in a debugger to verify for yourself. You may then learn a skill that you can apply to other problems in the future.
精彩评论