Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Sorry if the title is a little vague, my terminology isn't that great yet. What I'm t?rying to say is: which one is better in terms of memory management and if there is any difference Or which one is better to do in practice?

Say I have a function that will constantly update.

function update() {
    int i = random();
}

Here we constantly declare 'i' as an integer and give it a random number. This update will run untill program is terminated. Is this bad to do? How does memory deal with this? I imagine it's not much on its own like that, but maybe with bigger code it could affect things?

Is it better to just declare 'i' in the class header in any way, shape or form? Like it would allocate memory only ones for 'i'?

Still need to learn a lot on memory management, obviously :)

share|improve this question
    
@Dukeling thx for clarification .. I just wanted to bring it to any specific language .. As I though the issue is same for all language –  StinePike May 10 '13 at 19:57

1 Answer 1

It is always better to give your local variables the narrowest scope you can. So declaring within the loop is a good idea unless you want to use the variable outside the scope. In that case you need to declare it globally.

To be more clear check this so answers

answer 1, answer 2

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.