errno acts like an integer variable. A value (the error number) is stored in
errno by certain library functions when they detect errors. At program startup, the value stored is zero. Library functions store only values greater than zero. Any library function can alter the value stored before return, whether or not they detect errors. Most functions indicate that they detected an error by returning a special value, typically NULL for functions that return pointers, and -1 for functions that return integers. A few functions require the caller to preset
errno to zero and test it afterwards to see if an error was detected.
errno macro expands to an lvalue with type
int, sometimes with the
volatile type specifiers depending upon the platform. Originally this was a static memory location, but macros are almost always used today to allow for multi-threading, so that each thread will see its own thread-local error number.
- Results from a parameter outside a function's domain, e.g.
- Results from a result outside a function's range, e.g.
strtol("0xfffffffff",NULL,0)on systems with a 32-bit wide
EILSEQ (Required since 1994 Amendment 1 to C89 standard)
- Results from an illegal byte sequence, e.g.
mbstowcs(buf,"\xff", 1)on systems that use UTF-8.
POSIX compliant operating systems like AIX, Linux or Solaris include many other error values, many of which are used much more often than the above ones, such as EACCES for when a file cannot be opened for reading. C++11 additionally defines many of the same values found within the POSIX specification.
errno can be translated to a descriptive string using strerror (defined in string.h) or a BSD extension called
sys_errlist. The translation can be printed directly to the standard error stream using perror (defined in stdio.h). As
strerror in many Unix-like systems are not thread-safe, a thread-safe version
strerror_r is used, but conflicting definitions from POSIX and GNU makes it even less portable than the
- International Standard for Programming Language C (C11), ISO/IEC 9899:2011, p. 205
- International Standard for Programming Language C (C99), ISO/IEC 9899:1999, p. 186
- "Checking for Errors". The GNU C Library (glibc). GNU Project. 2014-02-08. Retrieved 2014-06-25.
- "A brief description of Normative Addendum 1". Retrieved 2013-09-12.
- The Single UNIX Specification, Issue 7 from The Open Group : system error numbers – Base Definitions Reference,
- "Error numbers - cppreference.com". Retrieved 2015-05-08.
- Stevens & Rago 2013, p. 14.
- McCabe, Colin. "The problem with strerror". www.club.cc.cmu.edu.