I searched all over the internet to know what does this means :
while(i++)
I've seen a lot of code similar at this. What does the incrementation return to the condition of the while loop ?
I searched all over the internet to know what does this means :
while(i++)
I've seen a lot of code similar at this. What does the incrementation return to the condition of the while loop ?
The construct i++
does two things. It evaluates to the current value of the variable i
, and it then increments the stored value by one. So, if i
is equal to -1
, then in the case of while(i++)
, i++
evaluates to -1
, which (being nonzero) is true, increments i
to 0
, the the loop body is executed, and on the next iteration, i++
evaluates to zero and increments i
to 1
, and zero being false, the while
finishes and execution proceeds beyond it.
The incrementation doesn't return anything to while loop condition.The value of the variable i
is first checked to be true a and then it is incremented.
True means anything not equal to 0
.
In while( i++ )
,value of i
is evaluated as condition of while
, after which i
is incremented by 1
. This is called as post increment in C which has side-effect.
Example,
i = 1;
while( i++ ) // same as while( i ),
// side-effect is `i` incremented by 1 after this
// now i is 2
Refer, this question for more information on increment operators.
you can try this code:
#include"stdio.h"
int main()
{
int i = -3;
while(i++)
printf("NUM I IS: %d\n",i);
i = -3;
printf("\n");
while(++i)
printf("NUM I IS: %d\n",i);
return 0;
}
the result is:
NUM I IS: -2
NUM I IS: -1
NUM I IS: 0
NUM I IS: -2
NUM I IS: -1
See, the second loop run only twice but first loop run 3th.
So
while(i++)
==>
while(i)
{
i = i +1;
...
}
And
while(++i)
==>
while( i = i+1)
WHILE
loop understands only two things i.e. TRUE
and FALSE
.
TRUE
=any value other than 0
FALSE
=0
If the condition is true, the loop will run otherwise, it will get terminated.
In your case, you say WHILE(i++)
that means you will keep incrementing the value of i & loop will go on until you get a 0
example:
i= -2;
WHILE(i++)
{
condition
}
In first loop, value of i will be -2
which is true. Condition will be executed & then i will be incremented. Thus, value of i now becomes-2+1 = -1
In second loop, value of i will be -1
which is true. Condition will be executed & then i will be incremented. Thus, value of i now becomes -1+1 = 0
In third loop, value of i will be 0
which is false. Thus loop gets terminated.