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
the function to be called on exit

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 a call to the exit function.

When using the MPLAB XC8 for PIC, a limit of 32 function handlers applies.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

#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