c - difference between return 1, return 0 and return -1 and exit? -
for example consider following code
int main(int argc,char *argv[]) { int *p,*q; p = (int *)malloc(sizeof(int)*10); q = (int *)malloc(sizeof(int)*10); if (p == 0) { printf("error: out of memory\n"); return 1; } if (q == 0) { printf("error: out of memory\n"); exit(0); } return 0; }
what return 0,return 1,exit(0) in above program.. exit(0) exit total program , control comes out of loop happens in case of return 0,return 1,return -1.
return
main()
equivalent exit
the program terminates execution exit status set value passed return
or exit
return
in inner function (not main
) terminate execution of specific function returning given result calling function.
exit
anywhere on code terminate execution immediately.
status 0 means program succeeded.
status different 0 means program exited due error or anomaly.
if exit status different 0 you're supposed print error message stderr
instead of using printf
better like
if(erroroccurred) { fprintf(stderr, "meaningful message here\n"); return -1; }
note (depending on os you're on) there conventions return codes.
also os may terminate program specific exit status codes if attempt invalid operations reading memory have no access to.
google "exit status codes" or similar , you'll find plenty of information on , elsewhere.
Comments
Post a Comment