while loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • momotaro
    Contributor
    • Sep 2006
    • 357

    while loop

    why these two versions of code don't give the same result?
    [CODE=c]
    int i = 0;
    while(i < MAXSIZE)
    {
    printf("%s\t%d\ n", emp_arr[i].name, emp_arr[i].age);
    i++;
    }
    //*************** ************and *************** ******

    int i = 0;
    while(i < MAXSIZE)
    printf("%s\t%d\ n", emp_arr[i++].name, emp_arr[i++].age);
    [/CODE]


    ain't they equivalent?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by momotaro
    why these two versions of code don't give the same result?

    ain't they equivalent?
    No they're not: the first loop is correct but the second loop even causes undefined
    behaviour because you're assigning a new value to a modifiable lvalue in an
    actual parameter list more than once. Use the first loop.

    kind regards,

    Jos

    Comment

    • xoinki
      New Member
      • Apr 2007
      • 110

      #3
      also, emp[i++].name causes name to be printed and i to be icremented.. so emp[i++].age would try to print the incremented value..
      (actually it may happen in the reverse direction.. first emp[i++].age then emp[i++].name)
      so it wont print same result

      regards,
      xoinki

      Comment

      • Matthew Page
        New Member
        • Jul 2007
        • 36

        #4
        Along the same lines as the last post, you are incrementing i twice instead of once for each loop iteration.

        Comment

        Working...