Does the gcc know to pull out declarations from frequently called functions?

I am working with the gcc5 compiler and I was wondering whether it is able to optimize the following code: Instead of

void mArray(int n) {
    double a[n];
    int x;
    // ... Do some things with a and x
}

int main(int argc, char *argv[])
{
    int i;
    for (i = 0; i < 1000000; i++)
    {
        mArray(argc);
    }
} 

can the compiler optimize this to

int main(int argc, char *argv[])
{
    int i;
    double a[argc];
    int x;
    for (i = 0; i < 1000000; i++)
    {
        // ... Do some things with a and x
    }
} 

Apart from the inlining, does the gcc compiler know how to pull these declarations and the corresponding memory allocations out of the loop in order to yield faster code?

1 answer

  • answered 2018-02-13 00:48 EJP

    does the gcc compiler know how to pull these declarations and the corresponding memory allocactions out of the loop

    The only memory allocation inside the loop is for the stack frame, which contains at least a base pointer and a return address, and the allocation occurs so by incrementing or decrementing the stack pointer register. Adding more space in the frame for the primitive variables costs nothing.

    in order to yield faster code?

    It would not yield faster code.

    Note that I am speaking about the code in your original question. I am not going to chase edits.