Error handling POSIX-style

POSIX-style error handling provides the most basic form of error handling possible, capable of being leveraged on almost any system, in almost any program. Written with standard C in mind, POSIX-style error handling takes the following form:

if (foo() != 0) {    std::cout << errno << '\n';}

Generally, each function called either returns 0 on success or -1 on failure, and stores the error code into a global (non-thread safe) implementation-defined macro, called errno. The reason 0 is used for success is that on most CPUs, comparing a variable to 0 is faster than comparing a variable to any other value, and the success case is the expected case. The following example demonstrates how this pattern is used:

#include <cstring> ...

Get Hands-On System Programming with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.