Home > front end >  For loop confusion
For loop confusion

Time:01-25

I have :

#include <stdio.h> 
int main(void) { 
int s,i,t[] = { 0, 1, 2, 3, 4, 5 }; 
s = 1; 
for(i = 2; i < 6 ; i  = i   1) 
s  = t[i]; 
printf("%d",s); 
return 0; 
}

Why is the result 8?

What I'm thinking:

first loop: 2<6 True
i =i 1 is 5
s=1 t[5] =>1 5=6
second loop : 5<6 True
i=5 5 2=11
s=6 t[11]???

CodePudding user response:

The loop increment expression (i = i 1 in your case) happens after the loop body, not before.

So in the first iteration you do

s = 1   t[2];

More generally, any for loop could be expressed as a while loop:

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

is equivalent to

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

For your specific case it's:

{
    i = 2;
    while (i < 6)
    {
        {
            s  = t[i]; 
        }

        i  = i   1;
    }
}

CodePudding user response:

I will guide you to the for loop reference:

iteration-expression is evaluated after the loop body and its result is discarded. After evaluating iteration-expression, control is transferred to cond-expression.

In your example, i = i 1, which is the iteration expression we're talking about, is evaluated after the loop body.

Taking this into account, the result will be 8

CodePudding user response:

Look attentively at the third expression in the for loop

s = 1; 
for(i = 2; i < 6 ; i  = i   1) 
s  = t[i];

It is i = i 1. So in iterations of the loop the variable i will be changed the following way

i = 2 (initially)
i = 5 ( i  = i   1 => i  = 2    1 => i  = 3 => i = 2   3)

After the second iteration of the loop the variable i will be already greater than 6. (i = i 1 => i = 5 1 => i = 6 => i = 5 6)

So this statement

s  = t[i];

in fact produces the following sum

1   t[2]   t[5] = 1   2   5

that is equal to 8.

  • Related