1

When I run this code, it enters an indefinite loop. Where did I go wrong?

#include <stdio.h>
int main()
{
    char x;                
    x=0;
    while(x<=225)
    {
        printf("%c=%d\n",x,x);
        x=x+1;
    }
    return 0;
}
4
  • 2
    The char is probably signed in your implementation so x has the range -128 to 127. Commented Jul 20, 2017 at 16:01
  • 1
    write unsigned char Commented Jul 20, 2017 at 16:01
  • oh.. misread 225 as 255... Commented Jul 20, 2017 at 16:02
  • @EugeneSh. me too. Who wouldn't? ;) Commented Jul 20, 2017 at 17:55

1 Answer 1

2

If the type char behaves as the type signed char then the valid range of values is [-128, 127]. It is undefined behavior when after increment the result value exceeds 127.

Instead of the type char you can use the type unsigned char.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.