0

I don't know what the use of exit() is

Consider the two following codes:

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

int main()
{
  int *ptr;

  if ((ptr = malloc(sizeof(int))) == NULL) {
    printf("Error");
    exit(EXIT_FAILURE);
  }
  exit(EXIT_SUCCESS);
}
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int *ptr;

  if ((ptr = malloc(sizeof(int))) == NULL) {
    printf("Error");
    return 1;
  }
  return 0;
}

What are the differences between the two of them ?

Kain
  • 329
  • 1
  • 10
  • 9
    If you're not in `main`, but in a different function, `return` will exit from that function and not from the whole program. – HolyBlackCat Aug 20 '21 at 13:30
  • 1
    In C (but not necessarily in C++) returning from the *initial* call to a standard `main()` has exactly the effect of calling `exit()` with the erstwhile return value as the argument. `exit()`, however, will terminate the program from anywhere within -- any function of any thread -- including from a reentrant call to `main()`. – John Bollinger Aug 20 '21 at 13:37

0 Answers0