Electronics > Beginners

post increment in for loop in C

<< < (2/2)

khatus:
Thnaks :)

forrestc:

--- Quote from: khatus on December 29, 2019, 07:04:31 am ---when j will be incremented ? is it before i or after i?

--- End quote ---

Walk through oPossum's code step by step.   Technically, i will be incremented after the loop containing j exits. 

But even though i is incremented after j, one should note that in reality what happens is that i counts from 1 to 2, and for each of the values of i, j counts from 1 to 2.

So your values inside the loop will be:

i=1 j=1
i=1 j=2
i=2 j=1
i=2 j=2

when the entire code exits, i will actually be 3 and so will j, since j got incremented to 3 which exited the inner loop, and i incremented to 3 which exited the outer loop.

One should note that this portion of your code:

--- Code: ---   if (i==j)
        continue;
       
    printf ("%d %d\n",i,j);

--- End code ---
is functionally equivalent to:

--- Code: ---if (i!=j) printf ("%d %d\n",i,j);

--- End code ---

The second form is easier to understand is generally considered better form.   Avoid using break and continue within a for loop since they can lead to unexpected bugs. 

forrestc:
Just a subtle terminology correction here, although what you meant came across fine:


--- Quote from: T3sl4co1l on December 29, 2019, 07:26:48 am ---i cannot possibly increment before j because i is out of scope, the j loop completes first.

--- End quote ---

In the case of the code shown, 'i' is not "out of scope".  Out of scope effectively means 'hidden'.  Because of the way that 'i' is declared, 'i' is in scope for the entire main() function (but not any other functions).   A bug in main() could definitely increment 'i' in the wrong spot and cause a program error.   For example, if one did something like:


--- Code: ---
int main()
{
    int i,j;
    for (i=1;i<=2;i++)
    {
        for(j=1;j<=2;i++)
        {
             if (i!=j)  printf ("%d %d\n",i,j);
        }   
     }   
     return(0);   
}

--- End code ---

(note the 'i' instead of a 'j' in the increment in the second for loop)

You'd find that the code would enter an infinite loop since you are (assumedly) accidentally incrementing 'i' within the 'j' loop instead of 'j'.   'j' never gets incremented so the loop never exits.  If 'i' was out of scope, the compiler would spit an error about not knowing about 'i'.   But since 'i' is actually within scope, the program can definitely increment i if you tell it to do so.

T3sl4co1l:
Scope isn't the right word for it, but the inner loop isn't touching the outer loop is the point.

magic:
single step it under debugger :P

Navigation

[0] Message Index

[*] Previous page

There was an error while thanking
Thanking...
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod