Consider the following situation:
I have a very long int main(). At the beginning, I declare and initialize an int. Shortly after, I use the int but don't need it again for the rest of the program.
For efficiency purposes, is there a way to free up the memory allocated to the int after it is no longer needed? Or, should I make it a *int and dynamically allocate the memory so I can delete it instead?
You can make scopes whereever you want. At the end of the scope, all the variables which were delared in that scope will be destroyed.
Example :
1 2 3 4 5 6 7 8
int main() {
int x = 0; //this will be visible until the end of main
{
int y; //this will be visible only in this scope
//...
}//y is not visible after this
//x still alive
}
Although, there are only a very few special cases where this kind of "optimization" is useful.
Most compilers will reuse unused variables anyway.
Don't dynamically allocate, that would very inefficient.
That brings up another thing I was wondering about: I was thinking of moving some stuff to functions to get it out of main() because it is used a few times, but is it worth it if it's only, say, 2-3 lines of code?
@HiteshVaghani1
For the reason OP asked, dynamically allocating a single int doesn't gain anything, since instead of the int take up memory on the stack an int* will, which is usually the same size. Not to mention the cost of allocating, deallocating and the added layer of redirection when dereferencing the pointer.