variable scope in for loop

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jeff Schwab

    #16
    Re: variable scope in for loop

    Andrey Tarasevich wrote:[color=blue]
    > Jeff Schwab wrote:
    >[color=green]
    >>...
    >>I think initialized variables properly does more for readability than
    >>making blocks of code look alike. Just my opinion, though.
    >>...[/color]
    >
    >
    > In my opinion, separating initialization of loop variable from the loop
    > itself might create more problems than delayed intialization of a variable.
    >[/color]

    For instance?

    Comment

    • Pete Becker

      #17
      Re: variable scope in for loop

      Jeff Schwab wrote:[color=blue]
      >
      > I think initialized variables properly does more for readability than
      > making blocks of code look alike. Just my opinion, though.[/color]

      Initializing variables isn't about readability, it's about limiting
      risk. If you're seriously concerned that you'll use loop index when it
      doesn't have a sensible value, then in addition to initializing it when
      you create it you need to reset it immediately after the first loop,
      just in case you refer to it before it gets reinitialized for the second
      loop. But, of course, that would look really stupid. At some point you
      have to think, instead of programming by cliche.

      --

      Pete Becker
      Dinkumware, Ltd. (http://www.dinkumware.com)

      Comment

      • Andrey Tarasevich

        #18
        Re: variable scope in for loop

        Jeff Schwab wrote:[color=blue][color=green]
        >>[color=darkred]
        >>>...
        >>>I think initialized variables properly does more for readability than
        >>>making blocks of code look alike. Just my opinion, though.
        >>>...[/color]
        >>
        >>
        >> In my opinion, separating initialization of loop variable from the loop
        >> itself might create more problems than delayed intialization of a variable.
        >>[/color]
        >
        > For instance?
        >[/color]

        For example, someone might inadvertently insert some other piece of code
        between the declaration of 'i' and the first cycle. If this new code
        happens to modify 'i' (let's say it is also a 'for' cycle on 'i') then
        the original first cycle will start with incorrect value of 'i'.

        C90-style of variable declaration is not really compatible with
        "declaratio n is an initialization" principle.

        In my opinion, it makes more sense to assign the initial value to the
        variable as close as possible to the spot where the effect of this
        assignment is used. In this partucular case this is achieved by placing
        the 'i = 0' expression inside each 'for' statement.

        --
        Best regards,
        Andrey Tarasevich

        Comment

        • Rolf Magnus

          #19
          Re: variable scope in for loop

          Pete Becker wrote:
          [color=blue]
          > Rolf Magnus wrote:[color=green]
          >>
          >> Wagner Bruna wrote:
          >>[color=darkred]
          >> > Hello,
          >> >
          >> > gokkog@yahoo.co m (Wenjie) wrote in message
          >> > news:<d2804eb3. 0401052346.1bcf 6d9b@posting.go ogle.com>...
          >> >>
          >> >> We had a code review with the argument of
          >> >> whether "i" is out of scope as illustrated
          >> >> below:
          >> >> for (int i=0; i<2004; i++)
          >> >> {
          >> >> doSomething(i);
          >> >> }
          >> >>
          >> >> for (i=0; i<2004; i++)
          >> >> {
          >> >> doSomethingElse (i);
          >> >> }
          >> >>
          >> >> Is it correct according to C++ language?
          >> >> VC++6.0 works fine with above code.
          >> >
          >> > No, it's not correct. The scope of i ends at the end of the first
          >> > loop.
          >> >
          >> > If you need VC++6 portability, a good workaround IMHO is to
          >> > enclosure the loops inside artificial blocks:
          >> >
          >> > {
          >> > for (int i=0; i<2004; i++) {
          >> > doSomething(i);
          >> > }
          >> > }
          >> >
          >> > {
          >> > for (int i=0; i<2004; i++) {
          >> > doSomethingElse (i);
          >> > }
          >> > }[/color]
          >>
          >> IIRC, another, less intrusive workaround is to
          >>
          >> #define for if(false); else for[/color]
          >
          > An even less intrusive workaround is to move the variable declaration
          > outside the loop:
          >
          > int i;
          > for (i=0; i<2004; i++)
          > {
          > doSomething(i);
          > }
          >
          > for (i=0; i<2004; i++)
          > {
          > doSomethingElse (i);
          > }[/color]

          You consider this less intrusive? You have to use that workaround in
          every function that has more than one for loop, while the macro only
          needs to be defined in one single place in a header that gets included
          everywhere. At the place where the for loop is, you don't need to take
          care about such things anymore.
          [color=blue]
          > Look, ma, no macros.[/color]

          So you wouldn't use that macro just for the sole sake of avoiding
          macros? Or do you have any real technical reason?

          Comment

          • Pete Becker

            #20
            Re: variable scope in for loop

            Rolf Magnus wrote:[color=blue]
            >
            > You consider this less intrusive? You have to use that workaround in
            > every function that has more than one for loop[/color]

            It's not a workaround. It's a way of writing portable code when you plan
            to target a compiler that doesn't support for loop scoping.
            [color=blue]
            > So you wouldn't use that macro just for the sole sake of avoiding
            > macros? Or do you have any real technical reason?[/color]

            Neither. Apparently you don't grasp humor.

            --

            Pete Becker
            Dinkumware, Ltd. (http://www.dinkumware.com)

            Comment

            • Rolf Magnus

              #21
              Re: variable scope in for loop

              Pete Becker wrote:
              [color=blue]
              > Rolf Magnus wrote:[color=green]
              >>
              >> You consider this less intrusive? You have to use that workaround in
              >> every function that has more than one for loop[/color]
              >
              > It's not a workaround. It's a way of writing portable code when you
              > plan to target a compiler that doesn't support for loop scoping.[/color]

              I'd not be willing to use that "way of writing code" if I don't need to.
              Well, actually, I'm not using VC++ myself, but if anyone wants to port
              my code to it, he either needs to change all the for loops (since I
              always define the counter in the for scope, which looks cleaner to me),
              or add the macro.
              [color=blue][color=green]
              >> So you wouldn't use that macro just for the sole sake of avoiding
              >> macros? Or do you have any real technical reason?[/color]
              >
              > Neither. Apparently you don't grasp humor.[/color]

              English is not my native tongue, so I might have difficulties to grasp
              your humor. Anyway, what's your point then?

              Comment

              • Howard

                #22
                Re: variable scope in for loop


                "Rolf Magnus" <ramagnus@t-online.de> wrote in message
                news:btfgsn$e7n $04$1@news.t-online.com...[color=blue]
                > Pete Becker wrote:
                >[color=green]
                > > Rolf Magnus wrote:[color=darkred]
                > >>
                > >> You consider this less intrusive? You have to use that workaround in
                > >> every function that has more than one for loop[/color]
                > >
                > > It's not a workaround. It's a way of writing portable code when you
                > > plan to target a compiler that doesn't support for loop scoping.[/color]
                >
                > I'd not be willing to use that "way of writing code" if I don't need to.
                > Well, actually, I'm not using VC++ myself, but if anyone wants to port
                > my code to it, he either needs to change all the for loops (since I
                > always define the counter in the for scope, which looks cleaner to me),
                > or add the macro.
                >[color=green][color=darkred]
                > >> So you wouldn't use that macro just for the sole sake of avoiding
                > >> macros? Or do you have any real technical reason?[/color]
                > >
                > > Neither. Apparently you don't grasp humor.[/color]
                >
                > English is not my native tongue, so I might have difficulties to grasp
                > your humor. Anyway, what's your point then?
                >[/color]

                Just an old expression used as a joke. Originally it was "look, ma, no
                hands"...used when doing something like riding your bicycle without using
                your hands.

                I think I agree with him that I'd just as soon not use macros. No real
                rechnical reason, I just don't like using them, I guess because you have to
                go look up what they do, try to figure out what the result of them is after
                parsing, and then they can be changed on you and you have to find everywhere
                they're used and be sure those places aren't broken. Just a pain in the
                arse if you ask me.

                Personally, I do it like you and write them according to the standard, with
                i declared within each for loop. Then, when I port to VC++ 6.0 (which I
                often do), I change the code that fails to compile and use a single
                declaration for i before the first loop.

                But I never use macros. (Templates are a pain in the ass to figure out
                sometimes, too, but their power is to great to ignore! :-))

                -Howard




                Comment

                • Jack Klein

                  #23
                  Re: variable scope in for loop

                  On Tue, 06 Jan 2004 14:41:03 -0500, Jeff Schwab <jeffplus@comca st.net>
                  wrote in comp.lang.c++:
                  [color=blue]
                  > Pete Becker wrote:[color=green]
                  > > Rolf Magnus wrote:
                  > >[color=darkred]
                  > >>Wagner Bruna wrote:
                  > >>
                  > >>
                  > >>>Hello,
                  > >>>
                  > >>>gokkog@yahoo .com (Wenjie) wrote in message
                  > >>>news:<d2804e b3.0401052346.1 bcf6d9b@posting .google.com>...
                  > >>>
                  > >>>>We had a code review with the argument of
                  > >>>>whether "i" is out of scope as illustrated
                  > >>>>below:
                  > >>>>for (int i=0; i<2004; i++)
                  > >>>>{
                  > >>>> doSomething(i);
                  > >>>>}
                  > >>>>
                  > >>>>for (i=0; i<2004; i++)
                  > >>>>{
                  > >>>> doSomethingElse (i);
                  > >>>>}
                  > >>>>
                  > >>>>Is it correct according to C++ language?
                  > >>>>VC++6.0 works fine with above code.
                  > >>>
                  > >>>No, it's not correct. The scope of i ends at the end of the first
                  > >>>loop.
                  > >>>
                  > >>>If you need VC++6 portability, a good workaround IMHO is to enclosure
                  > >>>the loops inside artificial blocks:
                  > >>>
                  > >>>{
                  > >>> for (int i=0; i<2004; i++) {
                  > >>> doSomething(i);
                  > >>> }
                  > >>>}
                  > >>>
                  > >>>{
                  > >>> for (int i=0; i<2004; i++) {
                  > >>> doSomethingElse (i);
                  > >>> }
                  > >>>}
                  > >>
                  > >>IIRC, another, less intrusive workaround is to
                  > >>
                  > >>#define for if(false); else for[/color]
                  > >
                  > >
                  > > An even less intrusive workaround is to move the variable declaration
                  > > outside the loop:
                  > >
                  > > int i;
                  > > for (i=0; i<2004; i++)
                  > > {
                  > > doSomething(i);
                  > > }
                  > >
                  > > for (i=0; i<2004; i++)
                  > > {
                  > > doSomethingElse (i);
                  > > }
                  > >
                  > > Look, ma, no macros.
                  > >[/color]
                  >
                  > I certainly prefer your macroless approach, but why not initialize i
                  > where it is defined, and save an assignment?
                  >
                  > int i = 0;
                  >
                  > for( ; i < 2004; ++i )
                  > do_something( i );
                  >
                  > for( i = 0; i < 2004; ++i )
                  > do_something_el se( i );[/color]

                  Because somebody maintaining your code some day, somebody else or even
                  you, will rearrange the loops or stick another one or another use for
                  'i' between the definition with initialization and the first for loop.
                  Then a perhaps strange and hard-to-find defect will be born.

                  The loop should perform its own initialization.
                  [color=blue]
                  > In production code, I tend to prefer while-loops to for-loops anyway, so
                  > it would look something like this:
                  >
                  > int i = 0;
                  >
                  > while( i < 2004 )
                  > {
                  > do_something( i );
                  > ++i
                  > }
                  >
                  > i = 0;
                  >
                  > while( i < 2004 )
                  > {
                  > do_something_el se( i );
                  > ++i;
                  > }
                  >
                  > I know folks are religious about for-loops; please don't be offended if
                  > I don't respond to criticisms about keeping loop control at the top of
                  > the block. :)[/color]

                  Nothing against while loops, I use them myself quite frequently, or
                  even do ... while loops, more often than most.

                  But I don't like an important condition of the loop separated from the
                  control statement itself, both for conceptual reasons and also for the
                  above mentioned maintenance problem. If someone, someday, puts
                  something between the initialization or the assignment and the
                  corresponding loop, bang!

                  In your particular example, I would use the for loop because it allows
                  setting the initial value of the control variable, a necessary
                  requirement of the loop, to appear in the loop control logic.

                  --
                  Jack Klein
                  Home: http://JK-Technology.Com
                  FAQs for
                  comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
                  comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                  alt.comp.lang.l earn.c-c++

                  Comment

                  • Jack Klein

                    #24
                    Re: variable scope in for loop

                    On Tue, 06 Jan 2004 16:32:01 -0500, Jeff Schwab <jeffplus@comca st.net>
                    wrote in comp.lang.c++:
                    [color=blue]
                    > Andrey Tarasevich wrote:[color=green]
                    > > Jeff Schwab wrote:
                    > >[color=darkred]
                    > >>...
                    > >>I think initialized variables properly does more for readability than
                    > >>making blocks of code look alike. Just my opinion, though.
                    > >>...[/color]
                    > >
                    > >
                    > > In my opinion, separating initialization of loop variable from the loop
                    > > itself might create more problems than delayed intialization of a variable.
                    > >[/color]
                    >
                    > For instance?[/color]

                    See my reply up-thread.

                    --
                    Jack Klein
                    Home: http://JK-Technology.Com
                    FAQs for
                    comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
                    comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                    alt.comp.lang.l earn.c-c++

                    Comment

                    • Gary Labowitz

                      #25
                      Re: variable scope in for loop

                      "Jack Klein" <jackklein@spam cop.net> wrote in message
                      news:89tmvvoqgk j3os54a67l78iub ocmopiahv@4ax.c om...
                      <<SNIP>>[color=blue]
                      > Nothing against while loops, I use them myself quite frequently, or
                      > even do ... while loops, more often than most.
                      >
                      > But I don't like an important condition of the loop separated from the
                      > control statement itself, both for conceptual reasons and also for the
                      > above mentioned maintenance problem. If someone, someday, puts
                      > something between the initialization or the assignment and the
                      > corresponding loop, bang!
                      >
                      > In your particular example, I would use the for loop because it allows
                      > setting the initial value of the control variable, a necessary
                      > requirement of the loop, to appear in the loop control logic.[/color]

                      We fought this problem of loop control for years in various shops and the
                      only bulletproof method we ever decided on was to use differently named loop
                      control variables in any block. While i, j, k seem traditional, presumably
                      left over from FORTRAN, it even makes for self-documenting code to use names
                      that mean something in the process being coded. Loop control variables like
                      addressVectorIt em for referencing an address in a Vector of addresses I feel
                      is better than just i. Long, fluffy names, that's the ticket!
                      --
                      Gary


                      Comment

                      • E. Mark Ping

                        #26
                        Re: variable scope in for loop

                        In article <3ffae75c$0$323 27$9a6e19ea@new s.newshosting.c om>,
                        Ron Natalie <ron@sensor.com > wrote:[color=blue]
                        >
                        >"Pete Becker" <petebecker@acm .org> wrote in message news:3FFAE1AE.A 12D3ED4@acm.org ...[color=green][color=darkred]
                        >> > #define for if(false); else for[/color]
                        >>
                        >> An even less intrusive workaround is to move the variable declaration
                        >> outside the loop:
                        >>
                        >> int i;
                        >>[/color]
                        >Actually, I find that MORE intrusive. You have to put sloppy coding
                        >practices in your code to correct for defects in the compiler.[/color]

                        You're saying that declaring the variable outside the loop is more
                        intrusive than using a macro to effectively redefine a language
                        keyword?

                        I find this baffling.
                        --
                        Mark Ping
                        emarkp@soda.CSU A.Berkeley.EDU

                        Comment

                        • Ron Natalie

                          #27
                          Re: variable scope in for loop


                          "E. Mark Ping" <emarkp@soda.cs ua.berkeley.edu > wrote in message news:bthq7l$200 3$1@agate.berke ley.edu...
                          [color=blue][color=green]
                          > >Actually, I find that MORE intrusive. You have to put sloppy coding
                          > >practices in your code to correct for defects in the compiler.[/color]
                          >
                          > You're saying that declaring the variable outside the loop is more
                          > intrusive than using a macro to effectively redefine a language
                          > keyword?
                          >
                          > I find this baffling.[/color]

                          I don't. The only thing I'm "redefining " here is making the keyword
                          behave like the language standard says it should. I pointed out that
                          it is technically wrong, but so is Microsoft, and I'd rather have standard
                          compliant code rather than Microsoft compliant code, we're portable
                          to platforms other than Windows.

                          By making this change, once, with the approval of our design team
                          and putting it in a controlled place, it gets around a zillion Microsoft
                          specific hacks that involve bad coding practices of leaving variables
                          uninitialized or sitting around outside the scope they are used in.

                          I'm not recommending the willy nilly redefining of keywords, but in
                          this case making the tested, controlled, one line change IS LESS
                          INTRUSIVE, than having to break standard-conforming code everywhere
                          else it appears OR adding bad programming practices because the
                          compiler is busted.

                          Comment

                          • Howard

                            #28
                            Re: variable scope in for loop


                            "Ron Natalie" <ron@sensor.com > wrote in message
                            news:3ffc3814$0 $31842$9a6e19ea @news.newshosti ng.com...[color=blue]
                            >
                            >
                            > By making this change, once, with the approval of our design team
                            > and putting it in a controlled place, it gets around a zillion Microsoft
                            > specific hacks that involve bad coding practices of leaving variables
                            > uninitialized or sitting around outside the scope they are used in.
                            >[/color]

                            I'm curious why you call it "bad coding practice" to have a single variable
                            used more than once. I understand that i is in this case just an integer,
                            and there's no logical reason why it *shouldn't* be declared in each for
                            loop construct, but what does it hurt to declare it once and use it multiple
                            times?

                            Imagine if you had, instead of an integer being used in multiple for loops,
                            some more complex object being used in multiple blocks of code within one
                            function. The overhead of constructing the object multiple times now can
                            outweigh the desired practice of declaring it within each block.

                            Personally, I prefer to declare i within each loop construct, and then
                            change that specific piece of code when I port to VC++. If I forget to
                            change it, the compiler tells me.

                            Provided that you do not rely on the value of i between or at the start of
                            any block, but instead assign it a value in the initializer portion of each
                            for loop, I fail to see where any harm can come from declaring it once and
                            using it multiple times. (And in the bad old days when I needed every byte
                            of memory I could get my grubby little hands on, it was practically a
                            *requirement* that I do it that way!)

                            -Howard



                            Comment

                            • Ron Natalie

                              #29
                              Re: variable scope in for loop


                              "Howard" <alicebt@hotmai l.com> wrote in message news:bthvop$6j3 @dispatch.conce ntric.net...
                              [color=blue]
                              >
                              > I'm curious why you call it "bad coding practice" to have a single variable
                              > used more than once. I understand that i is in this case just an integer,
                              > and there's no logical reason why it *shouldn't* be declared in each for
                              > loop construct, but what does it hurt to declare it once and use it multiple
                              > times?[/color]

                              Because why permit it to be inadvertantly used in expressions in between
                              the unrelated loops you're stuck using it in. Terribly non-structured.
                              [color=blue]
                              > Imagine if you had, instead of an integer being used in multiple for loops,
                              > some more complex object being used in multiple blocks of code within one
                              > function. The overhead of constructing the object multiple times now can
                              > outweigh the desired practice of declaring it within each block[/color]

                              If it were not something that made sense to be shared, it should be destroyed.
                              But you're inventing issues, by default variables should be defined in the smallest
                              scope that encompasses their use. THIS IS JUST PLAIN GOOD C++ DESIGN.
                              Having to thwart that because Microsnot can't get it right isn't a good reason
                              to chage the design rules.
                              [color=blue]
                              > Personally, I prefer to declare i within each loop construct, and then
                              > change that specific piece of code when I port to VC++. If I forget to
                              > change it, the compiler tells me.[/color]

                              If you do what I suggested, you don't have to go bastardizing your code
                              just because you have the misfortune of using Microsnot's compiler.

                              Comment

                              • Howard

                                #30
                                Re: variable scope in for loop


                                Microsnot? I'm telling Bill on you! :-)





                                Comment

                                Working...