Is constant integer division optimized compiler?

At first I feel that I have to defend myself. I know that I probably should not worry about this, premature optimization, and what not. I know. I ask about this solely because I am curious and cannot (or do not know how) find a solution on my own.

Is it common practice for compilers to optimize constant integer division? Something like that:

const int FOUR = 4; const int TWO = 2; int result = FOUR / TWO; 

Optimized:

 const int FOUR = 4; const int TWO = 2; int result = 2; 

Edit: I understand very well that the answer varies from compiler to compiler, I'm mostly wondering if its normal practice.

+4
source share
8 answers

Yes, this is almost a universal practice, in fact, if your compiler does not, you really have a very unusual compiler.

+6
source

More than usual, this is required for the language. If you declare the result const, it is an integral constant expression that can be used for things like array dimension. Therefore, the compiler must know the numerical value. This is one "optimization" that occurs even in assemblies where optimization is disabled.

+4
source

Yes, this is usually when optimization is enabled, however it will depend on the compiler. Visual C ++ 9 does this.

If you are really interested, you should check the emitted assembly - this is the only reliable way to find out.

+3
source

I will add that, although for integers OK, to do "permanent folding", problems with floats can occur, so this is not always done for / with them.

for instance

http://www.nullstone.com/htmls/category/consfold.htm

Some environments support several floating point rounding modes that can dynamically change at run time. In these environments, expressions such as (1.0 / 3.0) need to be evaluated at runtime if the rounding mode is not known at compile time.

+2
source

Yes, but think:

 void f(int x) { return x*3/4 } 

the order of operations means that 3/4 will not be shortened by the compiler

+2
source

I compiled and debugged a code very similar to yours, and, in my experience, I would say yes. But this can change the compiler-compiler (I mainly use MSC8-MSC10).

+1
source

This is called "persistent folding" in the compiler, and it is common on modern compilers. This is not just a separation that can be optimized; many types of constant expressions can be reduced to one compile-time constant.

+1
source

While the answer is yes for any popular compiler, I advise you to check the disassembly of your code in the debugger to see for yourself. Then you can learn skills that you can apply to other problems in the future.

+1
source

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


All Articles