atexit Function

Registers the specified function to be called when the program terminates normally.

Include

<stdlib.h>

Prototype

int atexit(void(*func)(void));

Argument

func
function to be called

Return Value

Returns a zero if successful; otherwise, returns a non-zero value.

Remarks

For the registered functions to be called, the program must terminate with the exit function call.

Example

#include <stdio.h>
#include <stdlib.h>

void good_msg(void);
void bad_msg(void);
void end_msg(void);

int main(void)
{
  int number;

  atexit(end_msg);
  printf("Enter your favorite number:");
  scanf("%d", &number);
  printf(" %d\n", number);
  if (number == 5)
  {
    printf("Good Choice\n");
    atexit(good_msg);
    exit(0);
  }
  else
  {
    printf("%d!?\n", number);
    atexit(bad_msg);
    exit(0);
  }
}

void good_msg(void)
{
  printf("That's an excellent number\n");
}

void bad_msg(void)
{
  printf("That's an awful number\n");
}

void end_msg(void)
{
  printf("Now go count something\n");
}

Example Input 1

With contents of UartIn.txt (used as stdin input for simulator):

5

Example Output 1

Enter your favorite number: 5
Good Choice
That's an excellent number
Now go count something

Example Input 2

With contents of UartIn.txt (used as stdin input for simulator):

42

Example Output 2

Enter your favorite number: 42
42!?
That's an awful number
Now go count something