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 ?
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 ?
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:
return
statement will just return the control to the caller functionexit()
will return the control to the host environment, after the following
atexit
functiontmpfile
function are removed.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
}
}