0

I have seen many posts regarding this question. Many say that exit(EXIT_SUCCESS) should be called for successful termination, and exit(EXIT_FAILURE) for unsuccessful termination.

  1. What I want to ask is: What if we do not call the exit() function and instead what if we write return 0 or return -1? What difference does it make?
  2. What happens if successful termination does not happen? What are its effects?

  3. It is told that if we call exit() functions the program becomes portable -- "portable" in the sense what? How can one function make the entire code portable?

  4. It is told that the execution returns to the parent what happens if the execution does not return to the parent?

My questions may seem to be silly but I need answers for all of these to get rid of my ambiguity between return and exit.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
srikar sana
  • 115
  • 1
  • 9
  • 1
    Possible duplicate of [return statement vs exit() in main()](http://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main) – GSerg Nov 21 '16 at 00:47
  • 1
    For (3), can you cite somewhere that says that. It doesn't make much sense as written. Which parent are you referring to in (4) — a parent process or a parent (calling) function? – Jonathan Leffler Nov 21 '16 at 03:29
  • in Linux `return -1;` will return 255 because the exit code is only 8 low bits. On Windows it'll return -1 – phuclv Nov 21 '16 at 04:02

1 Answers1

2
  1. Return returns a value from a function. Exit will exit your program. When called within the main function, they are essentially the same. In fact, most standard libc _start functions call main and then call exit on the result of main anyway.
  2. Nothing, directly. The caller (usually your shell) will get the return value, and be able to know from that whether your program succeeded or not.
  3. I don't know about this. I don't know what you mean here. exit is a standard function, and you may use it if you wish, or you can decide not to. Personally, I prefer to return from main only, and only return error status from other functions, to let the caller decide what to do with it. It's usually bad form to write an API that kills the program on anything but an unrecoverable error that the program can't manage.
  4. If execution didn't return to the parent (which is either a shell or some other program), it would just hang forever. Your OS makes sure that this doesn't happen in most ordinary cases.
Taywee
  • 1,313
  • 11
  • 17