C 标准库 - <errno.h>

C 语言变量 errno 是一个全局整数变量,库函数出错时被设置为对应的错误码。

定义

extern int errno;

定义于 <errno.h>,是一个线程局部(C11 起)的全局整数变量,库函数出错时设置对应错误码。

用法

#include <stdio.h>
#include <errno.h>
#include <math.h>

int main() {
    errno = 0;              // 调用前先清零
    double r = sqrt(-1);    // 域错误
    if (errno == EDOM)
        printf("数学域错误!\n");
    return 0;
}

输出:

数学域错误!

注意事项

调用库函数前先把 errno 设为 0,因为成功时它不会被自动清零。多线程场景用线程局部 errno。