Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Why not local loops?

  1. Nov 22, 2015 #1
    Once i did the following :

    for (int i=0;i <100;i++) {...}

    Hence with the i defined only in the loop and the professor told me we shall never do that.

    Do you know any reason ?

  2. jcsd
  3. Nov 22, 2015 #2


    Staff: Mentor

    The only reason I can think of is that compilers prior to the C99 spec didn't allow intermingling of declarations and executable statements, as you have in the for loop above. Other than that, I can't think of any reason why the above wouldn't be fine.
  4. Nov 22, 2015 #3
    I can't see anything really wrong with this.
    It sets up a loop which you want to iterate 100 times, and there could be a perfectly good reason why you want to do that.
    Possibly the tutor is objecting to the fact that no matter what goes on inside the loop, it's still always going to execute 100 times.
    It's generally more useful to have a loop which will terminate depending on some condition occurring inside the loop.
  5. Nov 22, 2015 #4


    User Avatar
    Gold Member

    Some instructors think that you should write a WHILE loop instead (and escape it on the appropriate condition), but really, people do the above all the time and I really don't have a problem with it. If you want to escape the loop before it goes 100 times, you can just use a break statement.
  6. Nov 22, 2015 #5


    Staff: Mentor

    Yes often we want to iterate an indexed array and at some condition being found escape with an index set of where we exitted the loop.
  7. Nov 22, 2015 #6


    User Avatar

    Staff: Mentor

    The OP didn't say anything about exiting the loop early. If I know I'm going to want to exit early, I normally write it as a while loop, myself.

    I took the question to be about declaring i as part of the loop initialization, which restricts its scope to inside the loop. I consider this to be a good thing, if you don't intend to use i outside the loop. It's like declaring local variables for a function instead of using global variables.

    If you want to use a variable named i somewhere else in the program, you have to declare it again outside the loop, and this means you actually have two separate variables named i. Changing the value of i inside the loop doesn't change its value outside the loop, and vice versa.
  8. Nov 22, 2015 #7


    Staff: Mentor

    I tend to use a for loop when I have something that is indexed and a while loop when I don't rather than having a while that increments an index. It just depends on which is more elegant to me at the time I'm writing the code.
  9. Nov 22, 2015 #8
    Yes, there is an aspect of programming as an art form, rather than 'engineering'.
    However in most employment, the employer doesn't give a damn as long as it works.
  10. Nov 23, 2015 #9


    User Avatar

    Staff: Mentor

    Someone will probably chime in about coding standards at many companies / organizations...
  11. Nov 23, 2015 #10
    I think the take-home lesson here is that there are different programming standards in different circumstances. Often, if you are working in a team, there will be standards that define style in an attempt to make all code look as though it came from the same author. The notion is that it can then be more readily reviewed or enhanced by other team members. In a lot of cases, I question the value of these standards - at some point, you need to be able to read anyone else's code and the main impediment to that is hardly in the style.
    There are also safety standards. For example, as I recall the MISRA standards, used in the automotive industry, advise against making variable declaration with statements such as the "for" statement. Again, the objective is to make the code more reviewable - especially in an environment where a bug could cost a life.
  12. Nov 23, 2015 #11
    Sure, I've worked for three companies, in my current position, I help set the standard. Your professor is wrong, in the real world you're supposed to declare a variable in as small of a scope as possible. In C, it's traditional to declare all of your variables at the top of your program, that allows it to just move the stack pointer once, but that's because C didn't make much use of an optimizer. C++ uses an optimizing compiler, so it works better if you limit your variables to only the scope that they are needed in. You're professor's opinion is about a decade out of date.

    This has been standard at all companies: DON'T REUSE VARIABLES!!! That's the biggest reason to declare it inline, to make sure that there isn't already an i somewhere.
  13. Nov 23, 2015 #12

    jim mcnamara

    User Avatar

    Staff: Mentor

    IIRC, C99 allowed declarations inside loops, in part, to help deal with "locality" issues. Commodity CPUs have "local" buffers with names like L2 or L1. Program code in those buffers can be accessed and executed quickly. Otherwise, the code from somewhere in slower RAM has to be accessed over and over again. The cost of accessing that code over and over again can be large when the code makes millions of iterations of a loop. Data may have the same problem, you can create a memory object that is too large to fit in the local buffers at one time. e.g. a gigantic array with millions of elements.

    IF this sounds at all interesting try:
    http://lwn.net/Articles/250967/ Start of the article there are 7 parts
    http://lwn.net/Articles/252125/ Part that speaks to CPU caches.
  14. Nov 23, 2015 #13


    User Avatar
    Science Advisor

    If you break out of the loop for some reason and you want to know afterwards if you did and for what value of i it happened, you may not be able to access a "localized" i. You can work around that, however, with a bit of thought and design before you code.

    I must admit to being an old-fashioned ANSI C programmer, so an "inline" declaration does not seem natural to me.
  15. Nov 23, 2015 #14


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    MISRA-C is a standard that is often applied to C code in airplanes and automobiles. The habit of declaring the index as you suggest would make it tempting to violate mandatory MISRA rule 21 (and maybe others):
    "Identifiers in an inner scope shall not use the same name as an identifier in an outer scope, and therefore hide that identifier".

    I am not sure what the history and rationalization of this rule is, but there is it and we often have to follow it.
    (see http://home.sogang.ac.kr/sites/gsinfotech/study/study021/Lists/b7/Attachments/91/Chap%207.%20MISRA-C%20rules.pdf [Broken] )

    PS. I advise against using a generic loop index like i or j. Better is row_index, column_index, student_index, etc. whatever you are looping through.
    Last edited by a moderator: May 7, 2017
  16. Nov 24, 2015 #15
    Agreed, i, j, x are nice and everyone uses them. It took me 10 years of writing code before I really got into the habit of explicitly naming variables like that, it's much easier to maintain later.
  17. Nov 24, 2015 #16
    In C++ in case you have same name variable in different scopes, the scope operator :: can be used. But it's true, using i,j,... is a bad habit, when writing small test codes maybe.
  18. Nov 24, 2015 #17


    Staff: Mentor

    From "Code Complete," by Steve McConnell,
    He also says that if the loop is longer than a few lines, or you have nested loops, it's better to use a more meaningful name for the loop index(es).
  19. Nov 24, 2015 #18
    Only if you name the scopes, which isn't done very often.

    Also, in a loop, you should use ++i instead of i++.
  20. Nov 27, 2015 #19

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    That depends on the language. C and C++ are rather different languages, despite suggestions from management such as "We need to hire a C/C++ programmer!"

    In C, the canonical form for a for loop is to use for (variable_name=initial; !final_condition; variable_name++)[ { ...} . Using ++variable_name in lieu of variable_name++ is a sign that the programmer may be doing something suspicious. It's exactly the opposite in C++. Using ++variable_name is the canonical form in C++; uing variable_name++ is a sign that something dubious might be happening.
  21. Nov 27, 2015 #20
    For the scope operator I thought naming were not mandatory ::i is just the previous scope ?

    As for D H i didn't know that point just i read once about the border effect that since the stack of the arguments is reverse we could obtain weird results

    Prinft ("%d,%d.",i,++i)

    Would print 11,11 ?
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook