Does the gcc optimize out local arrays the same way it would optimize out a local variable

arraycgcc

If I write this code in a function:

void func(void)
{
    int x = 0;
    int y = 3724832+x;
}

It would (probably) optimize the variable y out because it isn't being used. Even if I'm wrong about this specific case, the point I'm making is that the compiler has the ability to optimize out variables.

My question is does it also do this with local arrays?

Example:

void func(void)
{
    uint8_t tempBuffer[2] = {0x00, 0x01};
    sendBufferOverUSB(tempBuffer, 2); //sendBufferOverUSB(uint8_t* arr, int sizeArr);
}

Does the compiler then optimize this array out? Or does it keep this array in memory forever? Or is that even what optimization means? I know that arrays are created at compile time, so I'm trying to figure out if I should be using arrays in the way I've just used them or if I should make an array for every .c file as a buffer and simply use that whenever I need to store some bytes for transmission. Like this:

//example.c
#include "example.h"
#define MAX_EXAMPLE_BUFFER_SIZE 256
static uint8_t localBuffer[MAX_EXAMPLE_BUFFER_SIZE];
void func(void)
{
    // using buffer 
    localBuffer[0] = 0x00;
    localBuffer[1] = 0x01;
    sendBufferOverUSB(localBuffer, 2); //sendBufferOverUSB(uint8_t* arr, int sizeArr);
}

I am going to have a bunch of functions which need to convert from Little Endian variables into Big Endian formatted bytes so i essentially need some buffer to move these bytes into, and I just didn't know if making an array of the size needed was better than using a buffer for that .c file.

Best Answer

"Optimized out" means the compiler realises the variable isn't necessary, and deletes the variable. For example, this code:

void func(void)
{
    int x = 0;
    int y = 3724832+x;
    printf("%d\n", y);
}

might be compiled the same way as:

void func(void)
{
    printf("%d\n", 3724832);
}

or even (if your compiler is smart enough)

void func(void)
{
    puts("3724832");
}

and we would say that the variables x and y have been optimized out, because the optimizer has removed them from the program.

"Optimized out" does not mean that the variable gets destroyed when the function returns. All non-static local variables get destroyed when the function returns. No exceptions. This includes arrays.

In your function:

void func(void)
{
    uint8_t tempBuffer[2] = {0x00, 0x01};
    sendBufferOverUSB(tempBuffer, 2);
}

the variable tempBuffer will be destroyed when the function returns. If you try to trick the compiler so you can use tempBuffer after func returns - for example, using a pointer - you might find that the memory that used to contain this variable has been overwritten, and it no longer contains {0x00, 0x01}. You might even get a crash when you try to use it. This isn't because of optimization.