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.
uint8_t tempBuffer[2] = {0x00, 0x01};
is declared in a function locally, so it will be stored on the stack while the function executes, and gets popped off the stack (discarded) when the function exits.