int c = getchar()?

Unlike some other languages you may have used, chars in C are integers. char is just another integer type, usually 8 bits and smaller than int, but still an integer type.

So, you don’t need ord() and chr() functions that exist in other languages you may have used. In C you can convert between char and other integer types using a cast, or just by assigning.

Unless EOF occurs, getchar() is defined to return “an unsigned char converted to an int” (same as fgetc), so if it helps you can imagine that it reads some char, c, then returns (int)(unsigned char)c.

You can convert this back to an unsigned char just by a cast or assignment, and if you’re willing to take a slight loss of theoretical portability, you can convert it to a char with a cast or by assigning it to a char.

Leave a Comment