why i++ instead of ++i in for loops

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

    why i++ instead of ++i in for loops


    I have been reading various texts in C/ C++ and Java. The for lops all
    run along the lines of :



    int i ;

    for(i = 0 ; i < 4 ; i++)

    {

    .....

    }



    I understand the difference between ++i and i++, but I can not see why
    i++ is used in these loops when, as I understand it, the steping
    expression would be more alined to i = i + 1 in this type of case. The
    logic of i++ is not the same. The final result might but the evaluation
    process is not.



    Ok I realise at the end of the loop the value of i is the same which
    ever method you use. But that does not explaine why the preference.



    Also from what I can see at the assembly code level



    int i ;

    for(i = 0 ; i < 4 ; ++i)

    {

    .....

    }



    and



    int i ;

    for(i = 0 ; i < 4 ; i++)

    {

    .....

    }



    are exactly the same.



    Could some please explain the need to use i++ over ++i.


    --
    Posted via http://dbforums.com
  • Peter van Merkerk

    #2
    Re: why i++ instead of ++i in for loops

    * snip *
    [color=blue]
    > Could some please explain the need to use i++ over ++i.[/color]

    Strictly speaking there is no real need for i++, since "int x = i;
    ++i;" yields the same result as "int x = i++;". As you have noticed in
    for loops with int as loop variable using ++i or i++ doesn't make a
    difference with most compilers. Note that with iterators the ++i version
    may very well be more efficient than i++.

    --
    Peter van Merkerk
    peter.van.merke rk(at)dse.nl






    Comment

    • Rolf Magnus

      #3
      Re: why i++ instead of ++i in for loops

      newtothis wrote:
      [color=blue]
      >
      > I have been reading various texts in C/ C++ and Java. The for lops all
      > run along the lines of :
      >
      >
      >
      > int i ;
      >
      > for(i = 0 ; i < 4 ; i++)
      >
      > {
      >
      > ....
      >
      > }
      >
      >
      >
      > I understand the difference between ++i and i++, but I can not see why
      > i++ is used in these loops when, as I understand it, the steping
      > expression would be more alined to i = i + 1 in this type of case. The
      > logic of i++ is not the same. The final result might but the
      > evaluation process is not.[/color]

      For builtin types, it really doesn't matter. But in C++, you can write
      and operator++ for your own class. And then it might matter, becaure
      postfix ++ has to create a copy of the object so that the old value can
      be returned. If you don't need the return value, that copy is
      unnecessary. If the compiler doesn't do named return value
      optimization, that copy might even need to be copied again, and all
      that just to throw the result away. The postfix operator++ for an own
      class might look something like this:

      MyClass MyClass::operat or++(int)
      {
      MyClass retval(*this); // copy the object
      // do whatever is needed to "increment" the object
      reutrn retval; // return the copy by value
      }

      while prefix ++ might look like:

      MyClass& MyClass::operat or++()
      {
      // do whatever is needed to "increment" the object
      return *this; // return a refernce to the object
      }

      Therefore, it's considered a good habit to always use prefix ++ if the
      return value is not needed.

      Comment

      • Artie Gold

        #4
        Re: why i++ instead of ++i in for loops

        newtothis wrote:[color=blue]
        > I have been reading various texts in C/ C++ and Java. The for lops all
        > run along the lines of :
        >
        > int i ;
        >
        > for(i = 0 ; i < 4 ; i++)
        >
        > {
        > ....
        > }
        >
        > I understand the difference between ++i and i++, but I can not see why
        > i++ is used in these loops when, as I understand it, the steping
        > expression would be more alined to i = i + 1 in this type of case. The
        > logic of i++ is not the same. The final result might but the evaluation
        > process is not.[/color]

        Good call, "newtothis" !
        [color=blue]
        >
        > Ok I realise at the end of the loop the value of i is the same which
        > ever method you use. But that does not explaine why the preference.
        >
        > Also from what I can see at the assembly code level
        >
        > int i ;
        >
        > for(i = 0 ; i < 4 ; ++i)
        > {
        > ....
        > }
        >
        > and
        >
        > int i ;
        >
        > for(i = 0 ; i < 4 ; i++)
        > {
        > ....
        > }
        >
        > are exactly the same.
        >[/color]
        Which, by itself is irrelevant -- and only because a compiler can see
        that the return value of `i++', i.e. the original value of `i' is
        thrown
        away.[color=blue]
        >
        > Could some please explain the need to use i++ over ++i.
        >[/color]
        Sorry. Can't be done. ;-) There is no `need'.
        What there *is* is `force of habit'. Historical artifact. Custom. Idiom.

        While it is true that there is likely to be no difference in the
        generated code when dealing with basic types, there often *is* a
        difference -- and a potentially significant one -- when dealing with
        user defined types (where `++', prefix and postfix are overloaded
        operators).

        Again, good call. Using the prefix form in such loops is to be
        preferred -- it's just a hard habit to break!

        HTH,
        --ag
        [color=blue]
        >
        > --
        > Posted via http://dbforums.com[/color]



        --
        Artie Gold -- Austin, Texas
        Oh, for the good old days of regular old SPAM.

        Comment

        • Andrew Koenig

          #5
          Re: why i++ instead of ++i in for loops

          > I have been reading various texts in C/ C++ and Java. The for lops all[color=blue]
          > run along the lines of :[/color]
          [color=blue]
          > int i ;[/color]
          [color=blue]
          > for(i = 0 ; i < 4 ; i++)[/color]
          [color=blue]
          > {[/color]
          [color=blue]
          > ....[/color]
          [color=blue]
          > }[/color]
          [color=blue]
          > I understand the difference between ++i and i++, but I can not see why
          > i++ is used in these loops when, as I understand it, the steping
          > expression would be more alined to i = i + 1 in this type of case. The
          > logic of i++ is not the same. The final result might but the evaluation
          > process is not.[/color]
          [color=blue]
          > Ok I realise at the end of the loop the value of i is the same which
          > ever method you use. But that does not explaine why the preference.[/color]

          You have hit on one of the reasons that "Accelerate d C++" always uses the
          "++i" form unless something is going to be done with the value of the
          expression. So, for example, we would write

          ++i;

          instead of

          i++;

          but we would write

          n = a[i++];

          if it were appropriate to do so--the point being that the value of "i++" is
          used in the second example.

          Incidentally, instead of

          for (i = 0; i < 4; i++)

          we would write

          for (i = 0; i != 4; ++i)

          because that way, we can use the same general form of loop for all kinds of
          iterators in addition to integers.


          Comment

          • jeffc

            #6
            Re: why i++ instead of ++i in for loops


            "newtothis" <member45182@db forums.com> wrote in message
            news:3531211.10 67348081@dbforu ms.com...[color=blue]
            >
            > I understand the difference between ++i and i++, but I can not see why
            > i++ is used in these loops when, as I understand it, the steping
            > expression would be more alined to i = i + 1 in this type of case. The
            > logic of i++ is not the same. The final result might but the evaluation
            > process is not.
            > Ok I realise at the end of the loop the value of i is the same which
            > ever method you use. But that does not explaine why the preference.[/color]

            I think you've answered your own question. In that case, the result is the
            same so it really doesn't matter. If it doesn't matter, i++ seems more
            aesthetically pleasing to most people, since logically you see the variable
            first, and then you see what to do with it. If these were classes with
            member functions, it would look like this.

            Int i(1);
            i.increment();
            vs.
            increment().i;

            The first looks more natural.


            Comment

            • Howard

              #7
              Re: why i++ instead of ++i in for loops


              "Andrew Koenig" <ark@acm.org> wrote in message
              news:3xvnb.1974 00$0v4.15332398 @bgtnsc04-news.ops.worldn et.att.net...
              [color=blue]
              > ...So, for example, we would write
              >
              > ++i;
              >
              > instead of
              >
              > i++;
              >
              > but we would write
              >
              > n = a[i++];
              >
              > if it were appropriate to do so--the point being that the value of "i++"[/color]
              is[color=blue]
              > used in the second example.
              >[/color]

              What do you mean that "the value of "i++" is used in the second example"?
              If you're referring to n = a[i++], then the value that is used to index into
              a is i, not i++. The increment is done afterwards. If, instead, you're
              just saying that you should only use i++ when you need the value of i++,
              again, I don't see how you can get that value, except in a following
              statement, as in

              x = a[i++];
              n = a[i]; // here we use the incremented value of i

              I think I see what you were getting at, but your phrasing is a little
              confusing.

              -Howard




              Comment

              • Rolf Magnus

                #8
                Re: why i++ instead of ++i in for loops

                Howard wrote:
                [color=blue]
                >
                > "Andrew Koenig" <ark@acm.org> wrote in message
                > news:3xvnb.1974 00$0v4.15332398 @bgtnsc04-news.ops.worldn et.att.net...
                >[color=green]
                >> ...So, for example, we would write
                >>
                >> ++i;
                >>
                >> instead of
                >>
                >> i++;
                >>
                >> but we would write
                >>
                >> n = a[i++];
                >>
                >> if it were appropriate to do so--the point being that the value of
                >> "i++"[/color]
                > is[color=green]
                >> used in the second example.
                >>[/color]
                >
                > What do you mean that "the value of "i++" is used in the second
                > example"? If you're referring to n = a[i++], then the value that is
                > used to index into a is i, not i++.[/color]

                i and i++ have the same value. The value of postfix++ is the value that
                the operand had before the increment.
                [color=blue]
                > The increment is done afterwards.[/color]

                Right.
                [color=blue]
                > If, instead, you're just saying that you should only use i++ when you
                > need the value of i++, again, I don't see how you can get that value,[/color]

                int a = i++;

                now a has the value of i++.
                [color=blue]
                > except in a following statement, as in
                >
                > x = a[i++];
                > n = a[i]; // here we use the incremented value of i
                >
                > I think I see what you were getting at, but your phrasing is a little
                > confusing.[/color]

                You seem to be confused by the term "value of i++". The value of i++ is
                what you get when you e.g. assign "i++" to something, not the value of
                i after i++ has been executed.

                Comment

                • Andrew Koenig

                  #9
                  Re: why i++ instead of ++i in for loops

                  > > ...So, for example, we would write[color=blue][color=green]
                  > >
                  > > ++i;
                  > >
                  > > instead of
                  > >
                  > > i++;
                  > >
                  > > but we would write
                  > >
                  > > n = a[i++];
                  > >
                  > > if it were appropriate to do so--the point being that the value of "i++"
                  > > is used in the second example.
                  > >[/color]
                  >
                  > What do you mean that "the value of "i++" is used in the second example"?
                  > If you're referring to n = a[i++], then the value that is used to index[/color]
                  into[color=blue]
                  > a is i, not i++.[/color]

                  I meant exactly what I said: The value of i++ is used in the second
                  example. Now, as it happens, if i is an integer, then the value of i++ is a
                  copy of what the value of i was before i was incremented. If i is a
                  user-defined type, the value of i++ might be something different. Either
                  way, evaluating the expression a[i++] involves using the value of i++.


                  Comment

                  • Howard

                    #10
                    Re: why i++ instead of ++i in for loops


                    "Rolf Magnus" <ramagnus@t-online.de> wrote in message
                    news:bnm57f$sbn $07$1@news.t-online.com...[color=blue]
                    > Howard wrote:
                    >[color=green]
                    > >
                    > > "Andrew Koenig" <ark@acm.org> wrote in message
                    > > news:3xvnb.1974 00$0v4.15332398 @bgtnsc04-news.ops.worldn et.att.net...
                    > >[color=darkred]
                    > >> ...So, for example, we would write
                    > >>
                    > >> ++i;
                    > >>
                    > >> instead of
                    > >>
                    > >> i++;
                    > >>
                    > >> but we would write
                    > >>
                    > >> n = a[i++];
                    > >>
                    > >> if it were appropriate to do so--the point being that the value of
                    > >> "i++"[/color]
                    > > is[color=darkred]
                    > >> used in the second example.
                    > >>[/color]
                    > >
                    > > What do you mean that "the value of "i++" is used in the second
                    > > example"? If you're referring to n = a[i++], then the value that is
                    > > used to index into a is i, not i++.[/color]
                    >
                    > i and i++ have the same value. The value of postfix++ is the value that
                    > the operand had before the increment.
                    >[color=green]
                    > > The increment is done afterwards.[/color]
                    >
                    > Right.
                    >[color=green]
                    > > If, instead, you're just saying that you should only use i++ when you
                    > > need the value of i++, again, I don't see how you can get that value,[/color]
                    >
                    > int a = i++;
                    >
                    > now a has the value of i++.
                    >[color=green]
                    > > except in a following statement, as in
                    > >
                    > > x = a[i++];
                    > > n = a[i]; // here we use the incremented value of i
                    > >
                    > > I think I see what you were getting at, but your phrasing is a little
                    > > confusing.[/color]
                    >
                    > You seem to be confused by the term "value of i++". The value of i++ is
                    > what you get when you e.g. assign "i++" to something, not the value of
                    > i after i++ has been executed.
                    >[/color]

                    That's exactly where I was confused. Which is why I asked what he meant by
                    "the value of i++".

                    It seems very strange to refer to the "value of i++" unless you were
                    refering to the value you get by performing the ++ operation upon the i
                    variable, which is obviously not the intent. To me, it would be like
                    referring to the "value of 7+1", and intending to refer to the value 7
                    (before adding one), whereas in normal conversation, you'd be talking about
                    the value 8, which is what 7+1 is equal to. See why it's confusing (at
                    least to me)?

                    No argument here on the "truth" of what Andrew said...just confusion on the
                    terminology.

                    -Howard






                    Comment

                    • Rolf Magnus

                      #11
                      Re: why i++ instead of ++i in for loops

                      Howard wrote:
                      [color=blue]
                      >
                      > "Rolf Magnus" <ramagnus@t-online.de> wrote in message
                      > news:bnm57f$sbn $07$1@news.t-online.com...[color=green]
                      >> Howard wrote:
                      >>[color=darkred]
                      >> >
                      >> > "Andrew Koenig" <ark@acm.org> wrote in message
                      >> > news:3xvnb.1974 0[/color][/color][/color]
                      $0v4.15332398@b gtnsc04-news.ops.worldn et.att.net...[color=blue][color=green][color=darkred]
                      >> >
                      >> >> ...So, for example, we would write
                      >> >>
                      >> >> ++i;
                      >> >>
                      >> >> instead of
                      >> >>
                      >> >> i++;
                      >> >>
                      >> >> but we would write
                      >> >>
                      >> >> n = a[i++];
                      >> >>
                      >> >> if it were appropriate to do so--the point being that the value of
                      >> >> "i++"
                      >> > is
                      >> >> used in the second example.
                      >> >>
                      >> >
                      >> > What do you mean that "the value of "i++" is used in the second
                      >> > example"? If you're referring to n = a[i++], then the value that is
                      >> > used to index into a is i, not i++.[/color]
                      >>
                      >> i and i++ have the same value. The value of postfix++ is the value
                      >> that the operand had before the increment.
                      >>[color=darkred]
                      >> > The increment is done afterwards.[/color]
                      >>
                      >> Right.
                      >>[color=darkred]
                      >> > If, instead, you're just saying that you should only use i++ when
                      >> > you need the value of i++, again, I don't see how you can get that
                      >> > value,[/color]
                      >>
                      >> int a = i++;
                      >>
                      >> now a has the value of i++.
                      >>[color=darkred]
                      >> > except in a following statement, as in
                      >> >
                      >> > x = a[i++];
                      >> > n = a[i]; // here we use the incremented value of i
                      >> >
                      >> > I think I see what you were getting at, but your phrasing is a
                      >> > little confusing.[/color]
                      >>
                      >> You seem to be confused by the term "value of i++". The value of i++
                      >> is what you get when you e.g. assign "i++" to something, not the
                      >> value of i after i++ has been executed.
                      >>[/color]
                      >
                      > That's exactly where I was confused. Which is why I asked what he
                      > meant by "the value of i++".
                      >
                      > It seems very strange to refer to the "value of i++" unless you were
                      > refering to the value you get by performing the ++ operation upon the
                      > i
                      > variable, which is obviously not the intent. To me, it would be like
                      > referring to the "value of 7+1", and intending to refer to the value 7
                      > (before adding one), whereas in normal conversation, you'd be talking
                      > about
                      > the value 8, which is what 7+1 is equal to. See why it's confusing
                      > (at least to me)?[/color]

                      Seems logical to me:

                      int x = 3 + 1;

                      the value of 3 + 1 is 4, so x is set to 4.

                      int y = x;

                      the value of x is 4, so y is set to 4.

                      int f(int i)
                      {
                      return i+1;
                      }

                      y = f(x);

                      the value of f(x) is 5, so y is set to 5 now.

                      int g(int& i)
                      {
                      int retval = i;
                      ++i;
                      return retval;
                      }

                      y = g(x);

                      the value of g(x) is 4, so y is set to 4.

                      z = x++;

                      the value of x++ is 5, so z is set to 5 now.

                      Comment

                      • Howard

                        #12
                        Re: why i++ instead of ++i in for loops


                        "Rolf Magnus" <ramagnus@t-online.de> wrote in message
                        news:bnmaat$ir6 $06$1@news.t-online.com...
                        [color=blue]
                        > Seems logical to me:
                        >[/color]

                        Oh well. I find it confusing, you don't. We'll both live. :-)

                        -Howard




                        Comment

                        • newtothis

                          #13
                          Re: why i++ instead of ++i in for loops


                          So from what has been said, except for may be the situation of an
                          oveloaded operator, the only reason for ++i vs i++ in the for loop is
                          programmer preference.

                          This then is close to the arguments of underscore vs mixedcase
                          vqariables.

                          Personal preference.



                          Why then dont the writeres of texts explain this instead of trying to
                          lay down some form of undefinable law?



                          Thanks for these comments as it clears up some programming "rules"
                          people have tried to push on me.


                          --
                          Posted via http://dbforums.com

                          Comment

                          • Duane Hebert

                            #14
                            Re: why i++ instead of ++i in for loops

                            [color=blue]
                            > I think you've answered your own question. In that case, the result is[/color]
                            the[color=blue]
                            > same so it really doesn't matter. If it doesn't matter, i++ seems more
                            > aesthetically pleasing to most people, since logically you see the[/color]
                            variable[color=blue]
                            > first, and then you see what to do with it. If these were classes with
                            > member functions, it would look like this.[/color]

                            Actually that's not true. i++ has to create a temporary and ++i doesn't.
                            This may
                            not be a big deal when i is an int, but it gets pretty inefficient when i is
                            a larger type or
                            an iterator etc.


                            Comment

                            • Andrew Koenig

                              #15
                              Re: why i++ instead of ++i in for loops

                              > So from what has been said, except for may be the situation of an[color=blue]
                              > oveloaded operator, the only reason for ++i vs i++ in the for loop is
                              > programmer preference.[/color]

                              Not quite. There's no difference in practice if i is an integer variable,
                              but if it's an iterator, there may be a performance difference. There is
                              also the philosophical question of whether it's a good thing to ask the
                              machine to do work that you know is going to be discarded.
                              [color=blue]
                              > Why then dont the writeres of texts explain this instead of trying to
                              > lay down some form of undefinable law?[/color]

                              Some of them do.


                              Comment

                              Working...