#include <stdio.h>
int main() {
unsigned char var = -100;
for(var = 0; var <= 255; var++){
printf("%d ", var);
}
}
the output is attached below (run on codeblocks IDE version 16.01)
why is the output an infinite loop?
#include <stdio.h>
int main() {
unsigned char var = -100;
for(var = 0; var <= 255; var++){
printf("%d ", var);
}
}
the output is attached below (run on codeblocks IDE version 16.01)
why is the output an infinite loop?
This condition var <= 255
is always true for an unsigned char
, assuming CHAR_BIT
is 8 on your platform. So the loop is infinite since the increment will cause the variable to wrap (that's what unsigned arithmetic does in C).
This initialization:
unsigned char var = -100;
is not an error, it's simply annoying code. The compiler will convert the int
-100 to unsigned char
, following the rules in the language specification.
Because unsigned char overflow problem. So, remove =
in for loop condition.
for(var=0;var<255;var++){
}
For more information, See this stack overflow question.
You are using an unsigned char
and its possible range is 0-255.
You are running your loop from 0-255 (inclusive). The moment your variable goes to 256, it will be converted back to 0. Also, initial value -100 will be treated as +156, due to this possible range.
So, this leads to an infinite loop.
unsigned char
Range is 0 to 255.When var =255.When it is incremented we get value as 256 which cannot be stored in unsigned char.That is the reason why it is ending in infinite loop.And when you initialize var as -100.It will not show any error because it converts -100 to binary and takes the 1st eight bits.And the corresponding value will be the value of var