0
#include <stdio.h>                                        

int main()
{
    unsigned char ch; 

    for (ch=0; ch<=255; ch++)   
        printf ("\n%d %c", ch, ch); 
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
daya
  • 160
  • 2
  • 14

2 Answers2

4

Since ch is of type unsigned char, it can only contain values between 0 and 255. When you increment ch from 255, it wraps around to 0, so it's always less than or equal to 255 and thus the loop continues forever.

aardvarkk
  • 14,955
  • 7
  • 67
  • 96
1

For loop goes as such:

  1. Initialize
  2. Check condition
  3. Do body
  4. Do post action (increment in your case)
  5. Go to 2.

You have declared:

unsigned char ch;

Range for such a variable would be [0..255]. So the problem is once it hits 255 it goes into body since 255<=255 afterwards it gets incremented and becomes 0, which is again fine since 0<=255. Hence it is an infinite loop.

tgregory
  • 554
  • 3
  • 9
  • There is a doubt that when 'ch' gets incremented to 255, the condition is still satisfied then the printf ( ) should give 255 and the corresponding character and after that 'ch' gets incremented to 256 and now the condition becomes false and loop should be simply terminated. Please clarify.. – daya Jun 26 '17 at 16:01
  • @daya unsigned char is a single byte unsigned type, which may hold values from 0 up to 2^8-1, on the majority of systems values get wrapped around on overflow (although that is an undefined behaviour, if I'm not mistaken). Your printf is the culprit for your misunderstanding, neither %d nor %c are the valid specifier for an unsigned char, use %u instead. – tgregory Jun 26 '17 at 16:11
  • thanks for clearing doubt. – daya Jun 26 '17 at 16:50