-2

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);
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Manhooo
  • 115
  • 2
  • 6
  • 2
    What did you expect to happen? – trent Dec 23 '16 at 15:54
  • 3
    Think about the values that `a` goes through on each loop iteration before it reaches 0. (Do you understand why `a` will eventually reach 0?) – Bill the Lizard Dec 23 '16 at 15:54
  • 2
    To add to @BilltheLizard's comment, think specifically about the size of `a` in bits and what that means in terms of the possible numbers it can store. – Mad Physicist Dec 23 '16 at 15:58
  • @BilltheLizard Actually i don't understand.Is it about the ASCII? – Manhooo Dec 23 '16 at 16:01
  • 2
    @Manhooo No, this has nothing to do with ASCII. An `unsigned char` is as I explained in my answer a number between 0 and 255. ASCII is the conversion of a number between 0 and 255 (most often a `char`, signed or unsigned) to a character. – Donald Duck Dec 23 '16 at 16:04
  • Add a print statement to print out the values of `a` and `b` if you are still having trouble. – Mad Physicist Dec 23 '16 at 16:05

1 Answers1

6

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.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99