命名空间
变体
操作

errno

来自 cppreference.cn
< c‎ | error
定义于头文件 <errno.h>
#define errno /* implementation-defined */

errno 是一个预处理器宏(但请参见下文的注释),它展开为一个 线程局部(自 C11 起) 类型为 int 的可修改左值。 几个标准库函数通过将正整数写入 errno 来指示错误。 通常,errno 的值设置为 <errno.h> 中列出的错误代码之一,作为以字母 E 开头后跟大写字母或数字的宏常量。

errno 的值在程序启动时为 0,并且虽然允许库函数写入正整数到 errno,无论是否发生错误,但库函数从不将 0 存储在 errno 中。

库函数 perrorstrerror 可用于获取与当前 errno 值对应的错误条件的文本描述。

注意:在 C11 之前,C 标准具有矛盾的要求,因为它们说 errno 是一个宏,但说“未指定 errno 是宏还是使用外部链接声明的标识符”。 C11 修复了这一点,要求将其定义为宏(另请参见 WG14 N1338)。

[编辑] 示例

#include <errno.h>
#include <math.h>
#include <stdio.h>
 
void show_errno(void)
{
    const char *err_info = "unknown error";
    switch (errno)
    {
        case EDOM:
            err_info = "domain error";
            break;
        case EILSEQ:
            err_info = "illegal sequence";
            break;
        case ERANGE:
            err_info = "pole or range error";
            break;
        case 0:
            err_info = "no error";
    }
    fputs(err_info, stdout);
    puts(" occurred");
}
 
int main(void)
{
    fputs("MATH_ERRNO is ", stdout);
    puts(math_errhandling & MATH_ERRNO ? "set" : "not set");
 
    errno = 0;
    (void)(1.0 / 0.0);
    show_errno();
 
    errno = 0;
    (void)acos(+1.1);
    show_errno();
 
    errno = 0;
    (void)log(0.0);
    show_errno();
 
    errno = 0;
    (void)sin(0.0);
    show_errno();
}

可能的输出

MATH_ERRNO is set
no error occurred
domain error occurred
pole or range error occurred
no error occurred

[编辑] 参考

  • C23 标准 (ISO/IEC 9899:2024)
  • 7.5 错误 <errno.h> (页码: 待定)
  • K.3.1.3 errno 的使用 (页码: 待定)
  • K.3.2 错误 <errno.h> (页码: 待定)
  • C17 标准 (ISO/IEC 9899:2018)
  • 7.5 错误 <errno.h> (页码: 待定)
  • K.3.1.3 errno 的使用 (页码: 待定)
  • K.3.2 错误 <errno.h> (页码: 待定)
  • C11 标准 (ISO/IEC 9899:2011)
  • 7.5 错误 <errno.h> (页码: 205)
  • K.3.1.3 errno 的使用 (页码: 584)
  • K.3.2 错误 <errno.h> (页码: 585)
  • C99 标准 (ISO/IEC 9899:1999)
  • 7.5 错误 <errno.h> (页码: 186)
  • C89/C90 标准 (ISO/IEC 9899:1990)
  • 4.1.3 错误 <errno.h>

[编辑] 参见

标准 POSIX 兼容错误条件的宏
(宏常量) [编辑]
将对应于当前错误的字符串显示到 stderr
(函数) [编辑]
返回给定错误代码的文本版本
(函数) [编辑]
定义通用数学函数使用的错误处理机制
(宏常量) [编辑]
C++ 文档 for errno