user3109599
user3109599

Reputation: 15

Printing ASCII in C

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;
}

Upvotes: 0

Views: 5183

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201439

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 = �

Upvotes: 0

paddy
paddy

Reputation: 63471

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

Upvotes: 5

Related Questions