Home > Back-end >  for loop does not produce different value in C ( i, i )
for loop does not produce different value in C ( i, i )

Time:01-12

for (int i = 0; i < n 1;   i)
{
    sum = sum   i;
}

for (int i = 0; i < n 1; i  )
{
    sum = sum   i;
}

Two paragraphs are different because of i and i in function call argument.

but it works like i only starts with 0. Why does even i starts with 0?

CodePudding user response:

There are absolutely no difference between these two snippets. i vs i only matters when mixed with other operators in the same expression. Which is a bad idea most of the time, since i / i comes with a side effect.

CodePudding user response:

A generic for loop like

for (a; b; c)
{
    d
}

is equivalent to

{
    a;
    while (b)
    {
        d;
        c;
    }
}

Note how the "increment" expression is after the main statement of the loop body.

For your loops that means they will be equivalent to:

{
    int i = 0;
    while (i < n 1)
    {
        sum = sum   i;
        i  ;  // or   i
    }
}

Since the increment of i doesn't happen until after you calculate sum there's no practical difference between the loop. Both will lead to the exact same result.


On a side-note: Remember to explicitly initialize sum to zero before the loop, or it might have an indeterminate value (that could be seen as garbage).

  •  Tags:  
  • Related