I've been learning C recently.
I have difficulty understanding the result of the code below.
Why is b
255 at last?
unsigned char a=1;
int b=0;
do
{
b++;
a++;
}while(a!=0);
I've been learning C recently.
I have difficulty understanding the result of the code below.
Why is b
255 at last?
unsigned char a=1;
int b=0;
do
{
b++;
a++;
}while(a!=0);
An
unsigned char
can only take values between 0 and 255. In your code, at each iteration of the loop,a
andb
both get incremented by 1 untila
reaches 255. Whena
is 255 and should be incremented by 1 more, it would have been 256 but since anunsigned char
can only take values between 0 and 255,a
takes the value 0 instead of 256. Then, the loop stops because ofwhile(a!=0)
andb
will equal 256 - 1 = 255.