简体   繁体   中英

C Programming increment & decrement

for(i=0;i++<10;)
    {
        printf("%d\n",i);
    }

Why is it printing 1 to 10?

I know post increment happens after a loop, so why is it not showing 0? And why is it showing 10?

No .. in for loop first condition is checked.. and after that you are printing i For循环图

I think what you're looking for is do..while

i=0;
do{
   printf("%d\n",i);
}while(i++<10);

Let's label the elements of the loop:

for(/* 1 */ i=0; /* 2 */ i++<10; /* 4 */)
{
    /* 3 */ printf("%d\n",i);
}

Here's how things play out:

  1. i is initialized to 0 ;
  2. The result of i++ is compared to 10 ; as a side effect of this expression, i is incremented by 1 ;
  3. The updated value of i is printed out;
  4. If there were an expression here, it would be evaluated.

Steps 2 through 4 are repeated until i++ < 10 evaluates to false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM