Home > Software engineering >  literal division at compile time
literal division at compile time

Time:11-26

Assume the following code:

static int array[10];

int main ()
{
    for (int i = 0; i < (sizeof(array) / sizeof(array[0])); i  )
    {
        // ...
    }
}

The result of sizeof(array) / sizeof(array[0]) should in theory be known at compile time and set to some value depending on the size of the int. Even though, will the compiler do the manual division in run time each time the for loop iterates?

To avoid that, does the code need to be adjusted as:

static int array[10];

int main ()
{
    static const int size = sizeof(array) / sizeof(array[0]);
    for (int i = 0; i < size; i  )
    {
        // ...
    }
}

CodePudding user response:

You should write the code in whatever way is most readable and maintainable for you. (I'm not making any claims about which one that is: it's up to you.) The two versions of the code you wrote are so similar that a good optimizing compiler should probably produce equally good code for each version.

You can click on this link to see what assembly your two different proposed codes generate in various compilers:

https://godbolt.org/z/v914qYY8E

With GCC 11.2 (targetting x86_64) and with minimal optimizations turned on (-O1), both versions of your main function have the exact same assembly code. With optimizations turned off (-O0), the assembly is slightly different but the size calculation is still done at a compile time for both.

Even if you doubt what I am saying, it is still better to use the more readable version as a starting point. Only change it to the less readable version if you find an actual example of a programming environment where doing that would provide a meaningful speed increase for you application. Avoid wasting time with premature optimization.

CodePudding user response:

Even though, will the compiler do the manual division in run time each time the for loop iterates?

No. It's an integer constant expression which will be calculated at compile-time. Which is why you can even do this:

int some_other_array [sizeof(array) / sizeof(array[0])];

To avoid that, does the code need to be adjusted as

No.

See for yourself: https://godbolt.org/z/rqv15vW6a. Both versions produced 100% identical machine code, each one containing a mov ebx, 10 instruction with the pre-calculated value.

  • Related