Chapter 11: cin, assert, and abort

Introduction to Assertions and Aborts

Assertions and aborts are tools used to enforce program correctness and handle critical errors.

Assertions

Assertions are used to verify assumptions made by the program. When an assertion fails, the program is immediately halted.

#include <cassert> // for assert

int testVowel()
{
#ifdef NDEBUG
    // If NDEBUG is defined, asserts are compiled out.
    // Since this function requires asserts to not be compiled out, we'll terminate the program if this function is called when NDEBUG is defined.
    std::cerr << "Tests run with NDEBUG defined (asserts compiled out)";
    std::abort();
#endif

    assert(isLowerVowel('a'));

    return 0;
}

Aborts

The std::abort function is used to terminate the program abnormally.

#include <cstdlib> // for std::abort

void terminateProgram()
{
    std::cerr << "Critical error, aborting program.";
    std::abort();
}

Usage of std::cerr and std::exit

std::cerr is used for error output and diagnostic information.

std::cout << "Error: Could not divide by zero\n";
std::exit(1);

Handling Input with cin

Ignoring Input

To ignore everything up to and including the next '\n' character:

#include <limits> // for std::numeric_limits

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

End of File and Peek

Handling Extraction Failures

If an extraction fails, future requests for input extraction will silently fail until clear() is called.

if (std::cin.fail()) // same as (!std::cin)
{
    std::cin.clear(); // Put us back in 'normal' operation mode
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Remove the bad input
}

Example with cin

#include <iostream>
#include <limits>

void getInput()
{
    int x;
    std::cout << "Enter a number: ";
    std::cin >> x;

    if (std::cin.fail())
    {
        std::cin.clear(); // Put us back in 'normal' operation mode
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // And remove the bad input
        std::cerr << "Error: Invalid input\n";
    }
    else
    {
        std::cout << "You entered: " << x << '\n';
    }
}

Static Assertions

Static assertions are checked at compile time and cause a compile-time error if the condition is false.

static_assert(sizeof(long) == 8, "long must be 8 bytes");
static_assert(sizeof(int) >= 4, "int must be at least 4 bytes");

Buffers

A buffer is a piece of memory set aside for storing data temporarily while it is moved from one place to another.