0

I'm trying to write a program that'll print out all ASCII characters using for loops, but it keeps going on infinite loop unless I take out 127, am I doing something wrong or is that how ASCII behaves?

This will crash (infinite loop):

#include <stdio.h> int main (void) { for (char i = -128; i <= 127; i++) { printf("%d = %c\n", i, i); } return 0; } 

But this is fine:

#include <stdio.h> int main (void) { for (char i = -128; i < 127; i++) { printf("%d = %c\n", i, i); } printf("%d = %c\n", 127, 127); return 0; } 
6
  • 5
    i <= 127 is always true if i is a signed 8-bit char type. Commented Jan 9, 2014 at 20:59
  • 1
    Loop from 0 not -127, there's no negative value ASCII char Commented Jan 9, 2014 at 21:00
  • Twos Complement springs to mind. Commented Jan 9, 2014 at 21:01
  • 1
    What compiler version are you using, and what warnings do you have enabled? Ideally there would be a compiler warning that i <= 127 is always true, and you should investigate such warnings for possible bugs in your code. Commented Jan 9, 2014 at 21:03
  • 1
    Please note that "crash" is not the same as "infinite loop". In the first case, your program terminates abnormally. In the second case, your program continues to run happily for as long as you allow. Commented Jan 9, 2014 at 21:06

2 Answers 2

5

When the loop reaches 127, it is allowed to continue. Then, 127 is increased by 1. Because this is signed char, it wraps to -128, which still meets the looping condition. In fact, every value of signed char is less than or equal to 127

The more normal thing to do is use a larger data type such as int for your loop.

for (int i = 0; i < 256; i++) { printf("%d = %c\n", i, i); } 
Sign up to request clarification or add additional context in comments.

Comments

0

Because a signed char can never be greater then 127...

 #include <stdio.h> int main (void) { printf("%d = %c\n", (char) 128, (char) 128); printf("%d = %c\n", (char) -128, (char) -128); } 

Outputs

-128 = � -128 = � 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.