A result that I can't figure out

124 Views Asked by At

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);
1

There are 1 best solutions below

0
On BEST ANSWER

An unsigned char can only take values between 0 and 255. In your code, at each iteration of the loop, a and b both get incremented by 1 until a reaches 255. When a is 255 and should be incremented by 1 more, it would have been 256 but since an unsigned char can only take values between 0 and 255, a takes the value 0 instead of 256. Then, the loop stops because of while(a!=0) and b will equal 256 - 1 = 255.