0

In c code , return and exit from main behaving same ?

int main (int argc , char* argv[])
{
    exit(2);
}

and

int main (int argc , char* argv[])
{
    return 2;
}

when both of code called from another c , both of them will return 2 ?

paramikoooo
  • 177
  • 2
  • 16
  • 1
    Reading about [`exit()`](https://en.cppreference.com/w/c/program/exit) and [`main()`](https://en.cppreference.com/w/c/language/main_function) in C would probably be helpful (and bookmark that site). – WhozCraig May 21 '19 at 14:10

2 Answers2

2

In case of the main() function, calling exit() or using return statement in the end have same output observable from the host environment, they will both be returning the execution control to the environment.

However, in case of any user-defined function:

  • using return statement will just return the control to the caller function
  • calling exit() will return the control to the host environment, after the following
    • Call all functions registered by the atexit function
    • All open streams with unwritten buffered data are flushed, all open streams are closed, and all files created by the tmpfile function are removed.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 2
    There are subtle differences in `main()` between `return n;` and `exit(n);` under some unusual but not impossible circumstances. The one that's usually quoted is that if you use `setbuf()` or `setvbuf()` on an open file that is not closed before the `return` or `exit()` is executed, and if you supply an array that's local to main as the buffer, then the buffer goes out of scope leading to undefined behaviour as the file is closed if you use `return` whereas it stays defined if you call `exit()`. However, that is seldom a problem in real programs. – Jonathan Leffler May 23 '19 at 06:47
0

main should behave as if it had been called inside of exit() (exit(main(argc,argv))), so a return from main should be basically equivalent to exit(retval), except after returning from main, references to main's locals become invalid, whereas they remain valid if you call exit:

#include <stdlib.h>
#include <stdio.h>
int *addr;
void print_thru_ptr(void)
{
    printf("%d\n", *addr);
}
int main (int argc , char* argv[])
{
    int local=42;
    addr=&local;
    atexit(print_thru_ptr);
    if(1){
        exit(2); //will print 42
    }else{
        return 2; //would be undefined
    }
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142