×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

atexit() Function with Example in C++

C++ atexit() function: Here, we are going to learn about the atexit() function with example of cstdlib header in C++ programming language.
Submitted by IncludeHelp, on May 26, 2020

C++ atexit() function

atexit() function is a library function of cstdlib header. It is used to set a function that should be executed on exit. Sometimes we need to write such code (like freeing the memory occupied by the global variables, closing the file objects, etc) that should be executed when the program is going to exit, any user-defined can be written for it and that can be set as an exit function using atexit() function.

The function invokes automatically when the program terminates normally. The function should be a void type.

Syntax

Syntax of atexit() function:

C++11:

extern "C" int atexit (void (*func)(void)) noexcept;
extern "C++" int atexit (void (*func)(void)) noexcept;

Parameter(s)

  • func – represents the function to be called at program exit.

Return value

The return type of this function is int, it returns 0 if the function registered successfully; non-zero, otherwise.

Sample Input and Output

// defining the function
void function_name(void){
    // function code
}

// setting the function
atexit(function_name);

Example

C++ code to demonstrate the example of atexit() function:

// C++ code to demonstrate the example of
// atexit() function

#include <iostream>
#include <cstdlib>
using namespace std;

void function1(void)
{
    cout << "Bye, Bye..." << endl;
}

void function2(void)
{
    cout << "Tata, Tata..." << endl;
}

// main() section
int main()
{
    //setting the functions
    atexit(function1);
    atexit(function2);

    cout << "Hi, friends..." << endl;

    cout << "Input first number: ";
    int a;
    cin >> a;

    cout << "Input second number: ";
    int b;
    cin >> b;

    cout << a << "+" << b << " = " << a + b << endl;

    return 0;
}

Output

Hi, friends...
Input first number: 10
Input second number: 20
10+20 = 30
Tata, Tata...
Bye, Bye...

Reference: C++ atexit() function



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.