← Back to C Course | Chapter 12: Advanced Topics | Lesson 14 of 20

C errno.h

What is errno?

errno is a global integer variable that C library functions set to a specific error code when something goes wrong internally, giving your program a standardized way to find out what kind of failure just occurred instead of just knowing that a function returned an error value.

Example: What is errno?

c
#include <stdio.h>
#include <errno.h>
#include <math.h>
int main() {
	errno = 0;
	sqrt(-1.0);
	printf("%d", errno != 0);
	return 0;
}

Triggering Math Errors

Certain math.h functions set errno to EDOM when you pass an argument outside the mathematically valid domain (like sqrt() of a negative number) or to ERANGE when the correct result would be too large or small to represent, letting you distinguish a bad input from an overflowed result.

Example: Triggering Math Errors

c
#include <stdio.h>
#include <errno.h>
#include <math.h>
int main() {
	errno = 0;
	sqrt(-1.0);
	printf("%d", errno == EDOM);
	return 0;
}

Printing Error Messages

strerror() takes an errno-style integer code and returns a pointer to a human-readable string describing what that code means, which is far more useful for debugging or logging than printing the raw numeric error code by itself.

Example: Printing Error Messages

c
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
	errno = ENOENT;
	printf("%s", strerror(errno));
	return 0;
}

Using perror()

perror() prints a message you supply, followed by a colon and the description of whatever error is currently stored in errno, combining your own context ('failed to open file') with the system's explanation ('No such file or directory') in one line.

Example: Using perror()

c
#include <stdio.h>
#include <errno.h>
int main() {
	FILE *fp = fopen("nonexistent.txt", "r");
	if (fp == NULL) {
		perror("failed to open file");
	}
	return 0;
}

Clearing errno

C library functions never reset errno back to 0 on success, they only ever set it on failure, so a stale error code from a previous call can linger and mislead you. Setting errno = 0 immediately before an operation you want to check is the reliable way to detect whether that specific call actually failed.

Example: Clearing errno

c
#include <stdio.h>
#include <errno.h>
#include <math.h>
int main() {
	errno = 0;
	sqrt(4.0);
	printf("%d", errno);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.