C Programming - Control Instructions - Discussion
#include<stdio.h>
int main()
{
unsigned int i = 65535; /* Assume 2 byte integer*/
while(i++ != 0)
printf("%d",++i);
printf("\n");
return 0;
}
Here unsigned int size is 2 bytes. It varies from 0,1,2,3, ... to 65535.
Step 1:unsigned int i = 65535;
Step 2:
Loop 1: while(i++ != 0) this statement becomes while(65535 != 0). Hence the while(TRUE) condition is satisfied. Then the printf("%d", ++i); prints '1'(variable 'i' is already incremented by '1' in while statement and now incremented by '1' in printf statement)
Loop 2: while(i++ != 0) this statement becomes while(1 != 0). Hence the while(TRUE) condition is satisfied. Then the printf("%d", ++i); prints '3'(variable 'i' is already incremented by '1' in while statement and now incremented by '1' in printf statement)
....
....
The while loop will never stops executing, because variable i will never become '0'(zero). Hence it is an 'Infinite loop'.
So here:
#include<stdio.h>
int main()
{
unsigned int i = 65535; /* Assume 2 byte integer*/
while(i++ != 0)
printf("%d",++i);
printf("\n");
return 0;
}
When integer gets increment (i++) by 1 then value should be 0.
That does not satisfy the while loop condition. Therefore it must print /n (i.e No output) only once right
So why its infinite loop?
The output I am getting, after running this code is - 655376553965541655436554565547655496555165553655556555765559655
Although, our expectation is that compiler must switch to 0, if we increment 65535 (beyond the upper range of unsigned int). but it's printing beyond the limit like 65537, and then 65539.
What exactly happening ?
Here first the value of I is checked in while loop as 65535 which is not equal o zero so condition is true no as it is post increment value of I is 0 when it passes to printf statement.
As again printf uses pre increment 1 is printed also with this mechanism the value of I never get 0 in while loop so this whole loop gets executed infinite times.
But it's "post" increment hence, first increment as the reason says is 65535 != 0
Then it GETS INCREMENTED TO 0 ("POST INCREMENT").
THEN increment In printf thus prints 1, and goes on with odd values.
Hope this helped you.
if the program changed to :
#include<stdio.h>
int main()
{
unsigned int i = 65535; /* Assume 2 byte integer*/
while(i++ != 65539)
printf("%d",++i);
printf("\n");
return 0;
}
the output is "6553765539" not 13..... why this happened?
Then it is further incremented in printf so it shows 1.
Its because your compiler supports 65535 +, so during program execution, you will have increment of 2 in original value of 65535 (1 due to while condition, and 1 due to printf condition).
Hence output will be 655376553965541.