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.


The getchar() function returns an integer which is the representation of the character entered. If you enter the character A, you will get 'A' or 0x41 returned (upgraded to an int and assuming you're on an ASCII system of course).

The reason it returns an int rather than a char is because it needs to be able to store any character plus the EOF indicator where the input stream is closed.

And, for what it's worth, that's not really a good book for beginners to start with. It's from the days where efficiency mattered more than readability and maintainability.

While it shows how clever the likes of K&R were, you should probably be looking at something more ... newbie-friendly.

In any case, the last edition of it covered C89 and quite a lot has changed since then. We've been through C99 and now have C11 and the book hasn't been updated to reflect either of them, so it's horribly out of date.

Tags:

C

Getchar