Declaration of variables

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

    #1

    Declaration of variables

    I have always felt that you should only declared variables as needed,
    and implicitily it seems many authors to encourage it, but the other
    day a friend told me that declaring variables inside a loop wasn't good
    practice, something like:

    for(int i=0; i<size-1; ++i){
    int aux = array[i];
    array[i]=array[i+1];
    array[i+1]=aux;
    }

    should be written like:

    int aux;
    for(int i=0; i<size-1; ++i){
    aux = array[i];
    array[i]=array[i+1];
    array[i+1]=aux;
    }

    What do you think? Thaks!

  • Victor Bazarov

    #2
    Re: Declaration of variables

    Gaijinco wrote:[color=blue]
    > I have always felt that you should only declared variables as needed,
    > and implicitily it seems many authors to encourage it, but the other
    > day a friend told me that declaring variables inside a loop wasn't good
    > practice, something like:
    >
    > for(int i=0; i<size-1; ++i){
    > int aux = array[i];
    > array[i]=array[i+1];
    > array[i+1]=aux;
    > }
    >
    > should be written like:
    >
    > int aux;
    > for(int i=0; i<size-1; ++i){
    > aux = array[i];
    > array[i]=array[i+1];
    > array[i+1]=aux;
    > }
    >
    > What do you think? Thaks![/color]

    I think it's your friend who should _prove_ it to you that there is some
    advantage to his method.

    V
    --
    Please remove capital As from my address when replying by mail

    Comment

    • Artie Gold

      #3
      Re: Declaration of variables

      Gaijinco wrote:[color=blue]
      > I have always felt that you should only declared variables as needed,
      > and implicitily it seems many authors to encourage it, but the other
      > day a friend told me that declaring variables inside a loop wasn't good
      > practice, something like:
      >
      > for(int i=0; i<size-1; ++i){
      > int aux = array[i];
      > array[i]=array[i+1];
      > array[i+1]=aux;
      > }
      >
      > should be written like:
      >
      > int aux;
      > for(int i=0; i<size-1; ++i){
      > aux = array[i];
      > array[i]=array[i+1];
      > array[i+1]=aux;
      > }
      >
      > What do you think? Thaks!
      >[/color]
      Since `aux' is only meaningful inside the loop why not limit its scope
      to the block inside the loop?

      On the other hand, there are situations where you wouldn't want to do
      this, when, for example, the variable in question is of a type that
      requires significant construction overhead. This, however, seems not to
      be one of those situations. ;-)

      HTH,
      --ag

      --
      Artie Gold -- Austin, Texas
      I will (ir)regularly write about things that are important to me -- that I hope interest you. Of course, since I see most things as being political, that will be most of it.

      "You can't KISS* unless you MISS**"
      [*-Keep it simple, stupid. **-Make it simple, stupid.]

      Comment

      • Phlip

        #4
        Re: Declaration of variables

        Gaijinco wrote:
        [color=blue]
        > I have always felt that you should only declared variables as needed,
        > and implicitily it seems many authors to encourage it, but the other
        > day a friend told me that declaring variables inside a loop wasn't good
        > practice, something like:
        >
        > for(int i=0; i<size-1; ++i){
        > int aux = array[i];
        > array[i]=array[i+1];
        > array[i+1]=aux;
        > }
        >
        > should be written like:
        >
        > int aux;
        > for(int i=0; i<size-1; ++i){
        > aux = array[i];
        > array[i]=array[i+1];
        > array[i+1]=aux;
        > }
        >
        > What do you think? Thaks![/color]

        Your friend might think that the first code is slower. In some few similar
        cases it might indeed be slower. You shouldn't worry about that.

        Tell your friend that premature optimization is the root of all evil. The
        most important resource to optimize is programmer time. Programmers must
        write clean code first, because it's easy to make beautiful code fast than
        fast code beautiful.

        After your for loop ends, aux's only meaning is "the last variable in the
        array". Subsequent statements should not rely on the for loop "leaking" its
        last aux value out. If they want the last value in the array, they should
        get it themselves. They should decouple as much as possible from the rest
        of your program, including the statements just before them.

        Always give any identifier the narrowest scope and access possible. Don't
        use global variables or public data members. Never create a variable
        without giving it an initial value. Put all these rules together, and you
        have many reasons to put int aux inside the loop.

        --
        Phlip
        http://www.greencheese.org/ZeekLand <-- NOT a blog!!!

        Comment

        • Tomás

          #5
          Re: Declaration of variables

          Gaijinco posted:
          [color=blue]
          > I have always felt that you should only declared variables as needed,
          > and implicitily it seems many authors to encourage it, but the other
          > day a friend told me that declaring variables inside a loop wasn't good
          > practice, something like:
          >
          > for(int i=0; i<size-1; ++i){
          > int aux = array[i];
          > array[i]=array[i+1];
          > array[i+1]=aux;
          > }
          >
          > should be written like:
          >
          > int aux;
          > for(int i=0; i<size-1; ++i){
          > aux = array[i];
          > array[i]=array[i+1];
          > array[i+1]=aux;
          > }
          >
          > What do you think? Thaks![/color]


          Here's how I'd to do it:

          for (int aux, i = 0; i < size -1; ++i)
          {
          ...
          }


          If I had to pick one of the two ways you posted, then I'd put the
          variable declaration outside the for loop. Does it make a difference?
          Probably not... but at least your safe in the thought that memory isn't
          being continuously allocated and deallocated for each iteration of the
          loop.

          Also as another Artie said, if you dealing with something like an
          std::string, then definitely put it *outside* the loop.

          The final reason is that I like consistency; if I'm going to put
          std::string outside the loop, then I'll put an "int" outside the loop
          too.

          -Tomás

          Comment

          • Roland Pibinger

            #6
            Re: Declaration of variables

            On 6 Mar 2006 12:13:48 -0800, "Gaijinco" <gaijinco@gmail .com> wrote:
            [color=blue]
            >I have always felt that you should only declared variables as needed,
            >and implicitily it seems many authors to encourage it, but the other
            >day a friend told me that declaring variables inside a loop wasn't good
            >practice, something like:
            >
            >for(int i=0; i<size-1; ++i){
            > int aux = array[i];
            > array[i]=array[i+1];
            > array[i+1]=aux;
            >}
            >
            >should be written like:
            >
            >int aux;
            >for(int i=0; i<size-1; ++i){
            > aux = array[i];
            > array[i]=array[i+1];
            > array[i+1]=aux;
            >}[/color]

            Why? Both versions are essentially the same. The performance is the
            same. The second version is bad style because it doesn't obey to the
            'minimal scoping rule'.
            [color=blue]
            >What do you think? Thaks![/color]

            Your friend has gone astray. Lead him back to the right path.
            Roland Pibinger

            Comment

            • Tomás

              #7
              Re: Declaration of variables

              Tomás posted:
              [color=blue]
              > Gaijinco posted:
              >[color=green]
              >> I have always felt that you should only declared variables as needed,
              >> and implicitily it seems many authors to encourage it, but the other
              >> day a friend told me that declaring variables inside a loop wasn't[/color][/color]
              good[color=blue][color=green]
              >> practice, something like:
              >>
              >> for(int i=0; i<size-1; ++i){
              >> int aux = array[i]; array[i]=array[i+1]; array[i+1]=aux; }
              >>
              >> should be written like:
              >>
              >> int aux;
              >> for(int i=0; i<size-1; ++i){
              >> aux = array[i]; array[i]=array[i+1]; array[i+1]=aux; }
              >>
              >> What do you think? Thaks![/color]
              >
              >
              > Here's how I'd to do it:
              >
              > for (int aux, i = 0; i < size -1; ++i)
              > {
              > ...
              > }
              >
              >
              > If I had to pick one of the two ways you posted, then I'd put the
              > variable declaration outside the for loop. Does it make a difference?
              > Probably not... but at least your safe in the thought that memory isn't
              > being continuously allocated and deallocated for each iteration of the
              > loop.
              >
              > Also as another Artie said, if you dealing with something like an
              > std::string, then definitely put it *outside* the loop.
              >
              > The final reason is that I like consistency; if I'm going to put
              > std::string outside the loop, then I'll put an "int" outside the loop
              > too.
              >
              > -Tomás[/color]


              Furthermore, if your worried about scope, God gave us curly braces for a
              reason:

              int main()
              {
              //Some code

              {
              int aux;
              for (int i; i < size -1; ++i)
              {
              //Some Code
              }
              }

              //Some more code
              }


              -Tomás

              Comment

              • Phlip

                #8
                Re: Declaration of variables

                Tomas wrote:
                [color=blue]
                > Here's how I'd to do it:
                >
                > for (int aux, i = 0; i < size -1; ++i)
                > {
                > ...
                > }[/color]

                Why?

                The scope is not as narrow as possible. It's one tick wider, into a scope
                where it's not needed.
                [color=blue]
                > If I had to pick one of the two ways you posted, then I'd put the
                > variable declaration outside the for loop. Does it make a difference?
                > Probably not... but at least your safe in the thought that memory isn't
                > being continuously allocated and deallocated for each iteration of the
                > loop.[/color]

                That's premature optimization.

                Further, the earliest definitions of C state that storage for all local
                variables in a function allocate when the function enters, regardless of
                their scope. I'm sure The Standard has since mutilated that requirement,
                but I can't imagine a compiler doing it any other way.
                [color=blue]
                > Also as another Artie said, if you dealing with something like an
                > std::string, then definitely put it *outside* the loop.[/color]

                Why? Have you time tested it?

                What if std::string inside a loop fit in your CPU cache, but outside the
                loop it overflowed your cache and caused memory thrashing?
                [color=blue]
                > The final reason is that I like consistency; if I'm going to put
                > std::string outside the loop, then I'll put an "int" outside the loop
                > too.[/color]

                Then put it consistently inside the loop. This improves the odds it will go
                away!

                --
                Phlip
                http://www.greencheese.org/ZeekLand <-- NOT a blog!!!

                Comment

                • Marcus Kwok

                  #9
                  Re: Declaration of variables

                  "Tom?s" <NULL@null.null > wrote:[color=blue]
                  > The final reason is that I like consistency; if I'm going to put
                  > std::string outside the loop, then I'll put an "int" outside the loop
                  > too.[/color]

                  Found these quotes in the FAQ:

                  "Consistenc y is good, but it is not the greatest good" [29.5]

                  "The real problem is that people tend to worship consistency, and they
                  tend to extrapolate from the obscure to the common. That's not wise."
                  [10.19]

                  (Granted, they are talking about different situations, but nonetheless
                  they are good pieces of advice to keep in mind in general.)

                  --
                  Marcus Kwok

                  Comment

                  • Artie Gold

                    #10
                    Re: Declaration of variables

                    Tomás wrote:[color=blue]
                    > Gaijinco posted:
                    >
                    >[color=green]
                    >>I have always felt that you should only declared variables as needed,
                    >>and implicitily it seems many authors to encourage it, but the other
                    >>day a friend told me that declaring variables inside a loop wasn't good
                    >>practice, something like:
                    >>
                    >>for(int i=0; i<size-1; ++i){
                    >> int aux = array[i];
                    >> array[i]=array[i+1];
                    >> array[i+1]=aux;
                    >>}
                    >>
                    >>should be written like:
                    >>
                    >>int aux;
                    >>for(int i=0; i<size-1; ++i){
                    >> aux = array[i];
                    >> array[i]=array[i+1];
                    >> array[i+1]=aux;
                    >>}
                    >>
                    >>What do you think? Thaks![/color]
                    >
                    >
                    >
                    > Here's how I'd to do it:
                    >
                    > for (int aux, i = 0; i < size -1; ++i)
                    > {
                    > ...
                    > }
                    >
                    >
                    > If I had to pick one of the two ways you posted, then I'd put the
                    > variable declaration outside the for loop. Does it make a difference?
                    > Probably not... but at least your safe in the thought that memory isn't
                    > being continuously allocated and deallocated for each iteration of the
                    > loop.
                    >
                    > Also as another Artie said, if you dealing with something like an
                    > std::string, then definitely put it *outside* the loop.[/color]

                    I think you've overstated my comments to an extent; I'm not sure I would
                    call a std::string something that involves `significant construction
                    overhead'. In any event, as noted elsethread, it's an optimization in
                    any case and not to be undertaken lightly.[color=blue]
                    >
                    > The final reason is that I like consistency; if I'm going to put
                    > std::string outside the loop, then I'll put an "int" outside the loop
                    > too.[/color]

                    It's only worth the ugliness of doing that if it's demonstrably worth
                    that ugliness in terms of *needed* performance.

                    Whenever possible localilty is *good*!

                    Cheers,
                    --ag

                    --
                    Artie Gold -- Austin, Texas
                    I will (ir)regularly write about things that are important to me -- that I hope interest you. Of course, since I see most things as being political, that will be most of it.

                    "You can't KISS* unless you MISS**"
                    [*-Keep it simple, stupid. **-Make it simple, stupid.]

                    Comment

                    • Tomás

                      #11
                      Re: Declaration of variables

                      [color=blue]
                      > It's only worth the ugliness of doing that if it's demonstrably worth
                      > that ugliness in terms of *needed* performance.[/color]

                      When I write extra-special long complicated loops, I resort to brute force.
                      Here's a copy-paste of some of my latest code:


                      manual_loop_sco pe:
                      {
                      std::size_t i = 0;
                      std::size_t i_word = NumericInfo::ma x_divisions_eur o - 2;

                      manual_loop_beg in_iteration:
                      {
                      bool const& condition = i < (NumericInfo::m ax_divisions_eu ro -
                      1);

                      if ( !condition ) goto manual_loop_end ;

                      manual_loop_bod y:
                      {
                      if ( p_digit[0] || p_digit[1] || p_digit[2] )
                      {
                      if (others_beforeh and)
                      {
                      StringSystem::A ppendPALIncCoun ter( p_char, ( p_digit
                      [0] ? lang_attribs.se parator_comma : lang_attribs.se parator_and ) );
                      }

                      others_beforeha nd = true;
                      StringSystem::A ppendPALIncCoun ter( p_char,
                      GetSubThousandW ithUnitName( p_digit[0], p_digit[1], p_digit[2],
                      lang_attribs.un it_names[i_word] ) );
                      }
                      } // close manual_loop_bod y
                      }//close manual_loop_ite ration

                      manual_loop_con tinue:
                      {
                      ++i;
                      p_digit += 3;
                      --i_word;

                      goto manual_loop_beg in_iteration;

                      }//close manual_loop_con tinue

                      manual_loop_end : ;
                      }


                      Beauty is irrelevant.

                      -Tomás

                      Comment

                      • Gavin Deane

                        #12
                        Re: Declaration of variables


                        Tomás wrote:
                        [color=blue][color=green]
                        > > It's only worth the ugliness of doing that if it's demonstrably worth
                        > > that ugliness in terms of *needed* performance.[/color]
                        >
                        > When I write extra-special long complicated loops, I resort to brute force.
                        > Here's a copy-paste of some of my latest code:
                        >
                        >
                        > manual_loop_sco pe:
                        > {
                        > std::size_t i = 0;
                        > std::size_t i_word = NumericInfo::ma x_divisions_eur o - 2;
                        >
                        > manual_loop_beg in_iteration:
                        > {
                        > bool const& condition = i < (NumericInfo::m ax_divisions_eu ro -
                        > 1);
                        >
                        > if ( !condition ) goto manual_loop_end ;
                        >
                        > manual_loop_bod y:
                        > {
                        > if ( p_digit[0] || p_digit[1] || p_digit[2] )
                        > {
                        > if (others_beforeh and)
                        > {
                        > StringSystem::A ppendPALIncCoun ter( p_char, ( p_digit
                        > [0] ? lang_attribs.se parator_comma : lang_attribs.se parator_and ) );
                        > }
                        >
                        > others_beforeha nd = true;
                        > StringSystem::A ppendPALIncCoun ter( p_char,
                        > GetSubThousandW ithUnitName( p_digit[0], p_digit[1], p_digit[2],
                        > lang_attribs.un it_names[i_word] ) );
                        > }
                        > } // close manual_loop_bod y
                        > }//close manual_loop_ite ration
                        >
                        > manual_loop_con tinue:
                        > {
                        > ++i;
                        > p_digit += 3;
                        > --i_word;
                        >
                        > goto manual_loop_beg in_iteration;
                        >
                        > }//close manual_loop_con tinue
                        >
                        > manual_loop_end : ;
                        > }[/color]

                        You're joking, right? Have you ever worked on code that's developed or
                        maintained by more than one person?
                        [color=blue]
                        > Beauty is irrelevant.[/color]

                        If by "beauty" you mean "readabilit y through conformance to accepted
                        normal practice" then, no it's not irrelevant. It's more important than
                        anything else.

                        You're trolling aren't you.

                        Gavin Deane

                        Comment

                        • Jim Langston

                          #13
                          Re: Declaration of variables


                          "Tomás" <NULL@NULL.NULL > wrote in message
                          news:Or3Pf.6836 $j7.258407@news .indigo.ie...[color=blue]
                          >[color=green]
                          >> It's only worth the ugliness of doing that if it's demonstrably worth
                          >> that ugliness in terms of *needed* performance.[/color]
                          >
                          > When I write extra-special long complicated loops, I resort to brute
                          > force.
                          > Here's a copy-paste of some of my latest code:
                          >
                          >
                          > manual_loop_sco pe:
                          > {
                          > std::size_t i = 0;
                          > std::size_t i_word = NumericInfo::ma x_divisions_eur o - 2;
                          >
                          > manual_loop_beg in_iteration:
                          > {
                          > bool const& condition = i < (NumericInfo::m ax_divisions_eu ro -
                          > 1);
                          >
                          > if ( !condition ) goto manual_loop_end ;
                          >
                          > manual_loop_bod y:
                          > {
                          > if ( p_digit[0] || p_digit[1] || p_digit[2] )
                          > {
                          > if (others_beforeh and)
                          > {
                          > StringSystem::A ppendPALIncCoun ter( p_char, (
                          > p_digit
                          > [0] ? lang_attribs.se parator_comma : lang_attribs.se parator_and ) );
                          > }
                          >
                          > others_beforeha nd = true;
                          > StringSystem::A ppendPALIncCoun ter( p_char,
                          > GetSubThousandW ithUnitName( p_digit[0], p_digit[1], p_digit[2],
                          > lang_attribs.un it_names[i_word] ) );
                          > }
                          > } // close manual_loop_bod y
                          > }//close manual_loop_ite ration
                          >
                          > manual_loop_con tinue:
                          > {
                          > ++i;
                          > p_digit += 3;
                          > --i_word;
                          >
                          > goto manual_loop_beg in_iteration;
                          >
                          > }//close manual_loop_con tinue
                          >
                          > manual_loop_end : ;
                          > }
                          >
                          >
                          > Beauty is irrelevant.
                          >
                          > -Tomás[/color]

                          Thank you. I haven't seen a good example of spagetti code for a number of
                          years.


                          Comment

                          • Tomás

                            #14
                            Re: Declaration of variables

                            Gavin Deane posted:
                            [color=blue]
                            >
                            > Tomás wrote:
                            >[color=green][color=darkred]
                            >> > It's only worth the ugliness of doing that if it's demonstrably
                            >> > worth that ugliness in terms of *needed* performance.[/color]
                            >>
                            >> When I write extra-special long complicated loops, I resort to brute
                            >> force. Here's a copy-paste of some of my latest code:
                            >>
                            >>
                            >> manual_loop_sco pe: {
                            >> std::size_t i = 0;
                            >> std::size_t i_word = NumericInfo::ma x_divisions_eur o - 2;
                            >>
                            >> manual_loop_beg in_iteration: {
                            >> bool const& condition = i <
                            >> (NumericInfo::m ax_divisions_eu ro - 1);
                            >>
                            >> if ( !condition ) goto manual_loop_end ;
                            >>
                            >> manual_loop_bod y: {
                            >> if ( p_digit[0] || p_digit[1] || p_digit[2] )
                            >> {
                            >> if (others_beforeh and)
                            >> {
                            >> StringSystem::A ppendPALIncCoun ter( p_char, (
                            >> p_digit
                            >> [0] ? lang_attribs.se parator_comma : lang_attribs.se parator_and ) ); }
                            >>
                            >> others_beforeha nd = true;
                            >> StringSystem::A ppendPALIncCoun ter( p_char,
                            >> GetSubThousandW ithUnitName( p_digit[0], p_digit[1], p_digit[2],
                            >> lang_attribs.un it_names[i_word] ) ); }
                            >> } // close manual_loop_bod y
                            >> }//close manual_loop_ite ration
                            >>
                            >> manual_loop_con tinue: { ++i;
                            >> p_digit += 3; --i_word;
                            >>
                            >> goto manual_loop_beg in_iteration;
                            >>
                            >> }//close manual_loop_con tinue
                            >>
                            >> manual_loop_end : ; }[/color]
                            >
                            > You're joking, right? Have you ever worked on code that's developed or
                            > maintained by more than one person?[/color]

                            No.

                            [color=blue][color=green]
                            >> Beauty is irrelevant.[/color]
                            >
                            > If by "beauty" you mean "readabilit y through conformance to accepted
                            > normal practice" then, no it's not irrelevant. It's more important than
                            > anything else.[/color]

                            I don't go for "accepted normal practice" -- I write my own code my own way.
                            It's efficient, portable and bug free.

                            My labels make it quite clear what's going on.
                            [color=blue]
                            > You're trolling aren't you.[/color]

                            No, I'm actually writing loops using labels and the "goto" keyword. If you
                            find it that scary, maybe you sould Google for "goto" and see what all the
                            grown-ups do with it.


                            -Tomás

                            Comment

                            • peter koch

                              #15
                              Re: Declaration of variables


                              Artie Gold wrote:[color=blue]
                              > Gaijinco wrote:[color=green]
                              > > I have always felt that you should only declared variables as needed,
                              > > and implicitily it seems many authors to encourage it, but the other
                              > > day a friend told me that declaring variables inside a loop wasn't good
                              > > practice, something like:
                              > >
                              > > for(int i=0; i<size-1; ++i){
                              > > int aux = array[i];
                              > > array[i]=array[i+1];
                              > > array[i+1]=aux;
                              > > }
                              > >
                              > > should be written like:
                              > >
                              > > int aux;
                              > > for(int i=0; i<size-1; ++i){
                              > > aux = array[i];
                              > > array[i]=array[i+1];
                              > > array[i+1]=aux;
                              > > }
                              > >
                              > > What do you think? Thaks!
                              > >[/color]
                              > Since `aux' is only meaningful inside the loop why not limit its scope
                              > to the block inside the loop?
                              >
                              > On the other hand, there are situations where you wouldn't want to do
                              > this, when, for example, the variable in question is of a type that
                              > requires significant construction overhead. This, however, seems not to
                              > be one of those situations. ;-)[/color]

                              Even in those cases you should go for the innermost scope until
                              performance and experimentation tells you otherwise. If e.g. the
                              variable was a std::string, semantics differ when you put the string
                              outside the loop, and the extra work to reset the string at each
                              iteration might well be comparable to the cost of one constructor and
                              one destructor.

                              /Peter[color=blue]
                              >
                              > HTH,
                              > --ag
                              >
                              > --
                              > Artie Gold -- Austin, Texas
                              > http://goldsays.blogspot.com
                              > "You can't KISS* unless you MISS**"
                              > [*-Keep it simple, stupid. **-Make it simple, stupid.][/color]

                              Comment

                              Working...