Thread: Silly loop question

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    13

    Silly loop question

    Probably a stupid question... but is it generally more efficient to declare a variable within a loop, i.e.

    Code:
    for(i = 0; i<10; i++) {
    int n;
    n = someArray[i]; // for instance
    ... do some stuff with n
    }
    or outside of it, i.e.

    Code:
    int n;
    for(i = 0; i<10; i++) {
    n = someArray[i]; // for instance
    ... do some stuff with n
    }
    I'd always assumed the latter, but I've seen some examples of the former in what I thought was pretty optimised code.

    Thanks.

  2. #2
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    In C it should not matter, if all the other operations are the same.

    In C++, the latter style is more efficient for any datatype that has a constructor (because 'objname n;' actually causes code to be run). It should still be no better for ints though.

  3. #3
    Registered User cbastard's Avatar
    Join Date
    Jul 2005
    Location
    India
    Posts
    167
    I think the first one would be better if the variable is not to be used outside the loop.because in the former the variable will be destroyed as the loop ends.There by releasing the stack space.So it is more memorily efficient.

  4. #4
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    The variable just goes "out of scope," which is a programming language issue.

    If it is not used after a certain point in the subroutine, it's not as if the compiler isn't going to use that memory or that register for something else, unless it doesn't need to.

  5. #5
    Registered User cbastard's Avatar
    Join Date
    Jul 2005
    Location
    India
    Posts
    167
    If the variable is used outside the loop(means defined by latter).Compiler will definetly not use that memory unless it is overwritten by user.this memory will not be added to heap.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. For loop question
    By JuzMe in forum C++ Programming
    Replies: 11
    Last Post: 04-20-2009, 08:39 AM
  2. Loop question
    By kwood965 in forum C Programming
    Replies: 6
    Last Post: 10-29-2008, 11:12 PM
  3. simple for loop function question
    By felicityxiv in forum C Programming
    Replies: 7
    Last Post: 05-06-2006, 11:43 PM
  4. Please don't laugh...SIMPLE loop question!
    By the_lumin8or in forum C++ Programming
    Replies: 5
    Last Post: 03-31-2006, 01:08 PM
  5. A Silly Question!
    By MK4554 in forum C++ Programming
    Replies: 2
    Last Post: 01-13-2006, 02:49 PM