So lets say I have a huge variable in a function that I may or may not need depending on some event. Could I control when and if it needs to be defined?
Something like:
void something() {
if (ishugevarneeded == true) {
float hugeVar[100]; //But making this hugeVar usable for all the function.
}
}
Is this possible as a method to save memory when the var is not needed?
The function malloc() or calloc() returns a pointer to a block of memory you can use and subsequently release with free(). Those functions can be placed with an if() clause, and the pointer can be stored in a global variable, which will be accessible to your other routines.
There are pitfalls to this approach, mainly involving ensuring you are releasing the memory you allocated, and ensuring the routines that might use that memory don't try to use it if you haven't yet allocated it, or continue to use it after it is freed.
void something() {
float hugeVar[100]; //But making this hugeVar usable for all the function.
... the rest of your function code
}
allocates 100 floats on the stack (which is a lot by the way) but de-allocates the memory as soon as the function returns.
So in that case, no if statement is needed for the allocation.
The only problem is the size of the available stack.
That is the beauty of variables local to a function. They do that, without any mystery or management overhead, such as malloc(), free(), new, delete, etc. do.
It normally won't save any memory, because all local variables get allocated (on the stack) at the beginning of the function, even if they are in "local" blocks. Even if you create a separate function, optimization can end up defeating your attempts to optimize memory use.