Getting rid of unused variables

Jul 4, 2012 at 10:53am
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?
Jul 4, 2012 at 11:09am
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.
Jul 4, 2012 at 12:50pm
You can use *int that's the best way i think.. and delete it when you need not any more.
Jul 4, 2012 at 2:05pm
korshyadoo,

I have a very long int main().


You can make your main easier to read by putting logical chunks of code into functions and calling them from main.

This should also reflect your code design.

Use of functions can promote reuse of code, and is a "Divide & Conquer approach"
Jul 4, 2012 at 4:42pm
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?
Jul 4, 2012 at 8:45pm
A function is created when
1)there is long code
2)there is repeatetion of same concept again and again.
Jul 5, 2012 at 5:41pm
@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.
Last edited on Jul 5, 2012 at 5:41pm
Jul 5, 2012 at 5:55pm
but is it worth it if it's only, say, 2-3 lines of code?


Yes, you should never have to do the same code over again.
Topic archived. No new replies allowed.