Hacker News new | ask | show | jobs
by Someone 2292 days ago
”What if instead of a char, getchar() returned an Option<char>?”

Getchar doesn’t return a char; it returns an int (https://en.cppreference.com/w/c/io/getchar).

⇒ if C didn’t do automatic conversions from int to char, we would have that (in a minimalistic sense)

That wouldn’t work for ftell and malloc (and, in general, most of the calls that set errno), though.

1 comments

> Getchar doesn’t return a char; it returns an int

Dammit, I knew that. Thank you for flagging my blunder; being precise is really important in this case. The Linux manpage better explains the return value of getchar:

https://linux.die.net/man/3/getchar

"fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error."

getchar() needs to return an object the width of an unsigned char, but all the values in that range are taken by possible character values. The return type had to be expanded to int in order to accommodate the sentinel.

The alternative of using an algebraic type is superior because the end-of-stream condition has a different type (so to speak), and furthermore, the programmer has no choice but to deal with it because the character value comes wrapped inside an Option which must be stripped away before the character value can be used.

Really, you also want the type system to express all possible error conditions as well, since getchar() returning EOF can mean either that end-of-file was reached or that some other error occurred!

As someone who has written lots of C code and worked hard to account for all possibilities manually, I really appreciate it when the type system and APIs can express all possibilities and back me up.