Thread: exit() and return() in main(): what's the difference?

  1. #1
    Registered User
    Join Date
    Apr 2020
    Location
    Greater Philadelphia
    Posts
    26

    exit() and return() in main(): what's the difference?

    I've written a simple void function that merely displays a string, and registered it with atexit().

    This function is called regardless of whether I end main() with exit() or return().

    Are these statements then identical when used in main()?

    According to documentation, exit() closes all open files.

    If exit() always executes, is there any point in explicitly closing files at the end of the program?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by C17 Clause 5.1.2.2.3 Paragraph 1
    If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.
    Quote Originally Posted by Algonon
    If exit() always executes, is there any point in explicitly closing files at the end of the program?
    Yes. You make it clear that these files were open and hence should be closed, which then avoids leaving them open unnecessarily should more code be later added to the program.

    Of course, if this is a trivial one-off program, then there's no point, but such programs when written by experienced programmers can freely break all the rules of good practice as they deem fit.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To exit using return 1
    By yvan in forum C Programming
    Replies: 2
    Last Post: 03-04-2016, 03:26 PM
  2. return or exit
    By ch4 in forum C Programming
    Replies: 4
    Last Post: 02-21-2009, 12:12 PM
  3. exit() vs return()
    By kryptkat in forum C Programming
    Replies: 9
    Last Post: 10-21-2006, 11:26 AM
  4. Exit with Return
    By Aidman in forum Linux Programming
    Replies: 6
    Last Post: 12-28-2005, 10:17 AM
  5. main() return values and exit()
    By sean in forum C Programming
    Replies: 4
    Last Post: 06-12-2002, 02:11 PM

Tags for this Thread