Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

assert and NDEBUG: runtime checks you can disable

`assert` checks an internal program assumption at runtime. Defining `NDEBUG` can disable the check without evaluating its condition; it does not affect `static_assert`.

Version: ISO C++23; implementation support may vary

Syntax

#include <cassert>
assert(condition);

In C++23, assert(condition) from <cassert> is a function-like macro, not a function named std::assert. When enabled and reached during execution, it evaluates a scalar condition. If the result compares unequal to zero, execution continues. Otherwise, it writes a diagnostic to standard error and calls std::abort(), terminating the program abnormally. The diagnostic format is implementation-defined.

When <cassert> is included with NDEBUG defined, assert(condition) expands to ((void)0) and the condition is not evaluated. Only the presence of the definition matters: #define NDEBUG 0 also disables assertions. Each inclusion of the header uses the current state of NDEBUG; changing it later without including the header again does not change the existing definition of assert. A build label such as Release does not by itself control this.

Use assert for internal invariants, not for input validation, access control, or recoverable errors. Keep essential work such as ++count outside assertions. In C++23 the macro takes one argument: if the expression contains a comma not protected by parentheses, wrap the whole expression in an extra pair of parentheses.

static_assert is a language declaration, not a macro. It checks a constant expression at compile time; a failed static assertion makes the program ill-formed. NDEBUG cannot disable it.

Examples

#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <memory>
#include <string>
#include <sys/wait.h>
#include <unistd.h>

#undef NDEBUG
#include <cassert>

static void check_enabled(int argc)
{
    assert(argc == 1);
}

#define NDEBUG
#include <cassert>

static void check_disabled([[maybe_unused]] int argc)
{
    assert(argc == 1);
}

static constexpr char next_statement[] = "Reached the next statement.";

static bool read_output(std::FILE* file, std::string& text)
{
    if (std::fseek(file, 0, SEEK_SET) != 0)
        return false;
    char buffer[256];
    while (const auto n = std::fread(buffer, 1, sizeof buffer, file))
        text.append(buffer, n);
    return !std::ferror(file);
}

static bool run(const char* executable, const char* name, const char* extra,
                bool should_abort, std::string& transcript)
{
    using File = std::unique_ptr<std::FILE, decltype(&std::fclose)>;
    File out(std::tmpfile(), &std::fclose);
    File err(std::tmpfile(), &std::fclose);
    if (!out || !err)
        return false;

    const pid_t child = fork();
    if (child < 0)
        return false;
    if (child == 0) {
        if (dup2(fileno(out.get()), STDOUT_FILENO) < 0 ||
            dup2(fileno(err.get()), STDERR_FILENO) < 0)
            _exit(126);
        // Re-execute this binary with the displayed name as argv[0].
        if (extra)
            execlp(executable, name, extra, static_cast<char*>(nullptr));
        else
            execlp(executable, name, static_cast<char*>(nullptr));
        _exit(127);
    }

    int status;
    pid_t waited;
    do {
        waited = waitpid(child, &status, 0);
    } while (waited < 0 && errno == EINTR);
    if (waited != child)
        return false;

    std::string stdout_text, stderr_text;
    if (!read_output(out.get(), stdout_text) || !read_output(err.get(), stderr_text))
        return false;
    if (should_abort) {
        if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT ||
            !stdout_text.empty() || stderr_text.empty())
            return false;
    } else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0 ||
               stdout_text != std::string(next_statement) + '\n' || !stderr_text.empty()) {
        return false;
    }

    transcript += name;
    if (extra) {
        transcript += ' ';
        transcript += extra;
    }
    transcript += "\n  stdout: ";
    if (should_abort) {
        transcript += "empty\n  stderr: assertion diagnostic (exact text varies)\n"
                      "  Abnormal termination via std::abort().\n";
    } else {
        transcript += stdout_text;
    }
    return true;
}

int main(int argc, char** argv)
{
    if (std::strcmp(argv[0], "./assert-on") == 0) {
        check_enabled(argc);
    } else if (std::strcmp(argv[0], "./assert-off") == 0) {
        check_disabled(argc);
    } else {
        std::string transcript = "Expected results:\n";
        if (!run(argv[0], "./assert-on", nullptr, false, transcript) ||
            !run(argv[0], "./assert-on", "extra", true, transcript) ||
            !run(argv[0], "./assert-off", "extra", false, transcript)) {
            std::fputs("Unexpected result from an assertion test run.\n", stderr);
            return 1;
        }
        transcript.pop_back();
        return std::fputs(transcript.c_str(), stdout) == EOF ? 1 : 0;
    }
    std::puts(next_statement);
}

Result

Expected results:
./assert-on
  stdout: Reached the next statement.
./assert-on extra
  stdout: empty
  stderr: assertion diagnostic (exact text varies)
  Abnormal termination via std::abort().
./assert-off extra
  stdout: Reached the next statement.

With assertions enabled, running without an extra argument prints `Reached the next statement.`; with `extra`, the program writes a diagnostic to standard error and aborts before printing that line. The build with `NDEBUG` prints the line even with `extra` because it does not evaluate `argc == 1`.

Related lessons

  • C++ · Lesson 49 · Intermediate · Version: 2

Sources