首页 > 解决方案 > 在 C 中无效的用户输入应该返回哪个 errno?

问题描述

假设我有一个 C 语言程序,我要求用户输入一个介于 1 和 3 之间的数字。如果用户选择了超出范围的数字,哪个errno最适合在我的函数中返回?

标签: cerrno

解决方案


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.


推荐阅读