Phoenix
Phoenix

Reputation: 420

Which errno should be returned on invalid user input in C?

Say I had a program in C where I asked the user to enter a number between 1 and 3. If the user selected a number outside of the range, which errno would be most appropriate to return in my function?

Upvotes: 0

Views: 619

Answers (2)

John Kugelman
John Kugelman

Reputation: 361565

I wouldn't use errno for a simple user-facing function like that. errno is mostly for system calls that are reporting low-level I/O, process, and other OS errors. It's not designed for things like bad keyboard input, incorrect file contents, or out of range values. When it's used by user libraries it's typically when they are forwarding internal system errors to the caller and don't want to bother creating an opaque error mechanism to wrap errno.

For example, a JSON library or a TLS encryption library might forward errno values from any failed I/O calls they perform. A multiprocessing library might forward errno values from failed fork/clone syscalls.

That said, if you still want to use errno, EINVAL Invalid Argument is reasonable.

Upvotes: 2

coreyp_1
coreyp_1

Reputation: 319

There is no "most appropriate" error number, per-se.

0 means no error. Anything non-0 means that there was an error. But because every program is unique, the errors that may be associated with that program are also unique.

You, as the programmer, determine what the error code means, and you communicate that to the end user by providing documentation. It really is that simple (and flexible).

Upvotes: -1

Related Questions