abort() function in C++

In this guide, you will learn what is abort() function is in C++ programming and how to use it with an example.

1. abort() Function Overview

The abort() function is used to terminate a program immediately without executing any further code or performing cleanup tasks. The function generates a SIGABRT signal, which can be caught by signal handling mechanisms; if not caught, it will terminate the program. It is a part of the C standard library <cstdlib> in C++.

Signature:

void abort(void);

Parameters:

None.

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    std::cout << "This will be printed." << std::endl;

    abort();  // Terminate the program

    std::cout << "This won't be printed." << std::endl;

    return 0;
}

Output:

This will be printed.
(Abort trap: 6 or similar system-specific abort message.)

3. Explanation

1. The program begins by printing "This will be printed." to the console.

2. Upon encountering the abort() function, the program is terminated immediately.

3. Consequently, "This won't be printed." is not printed, and the program does not return a value.


Comments