Jun 122012
 
 C++ Tags:,  Add comments

What is the difference between exit(0) and return statement in the main function of a C++ program?

Solution:

When exit(0) is used to exit from a C++ program, the destructor for local non-static objects is not called.

    class MyClass
    {
        public:

        // Constructor
        MyClass() { cout<< "Constructor" << endl; }

        // Destructor
        MyClass() { cout<< "Destructor" << endl; }
    };

    int main()
    {
        MyClass obj; 

        // Using exit
        exit(0);
    }

Output:

Constructor

If we do a return from the main, then implementation will make sure that the destructor is called

    class MyClass
    {
        public:

        // Constructor
        MyClass() { cout<< "Constructor" << endl; }

        // Destructor
        MyClass() { cout<< "Destructor" << endl; }
    };

    int main()
    {
        MyClass obj; 

        // Using return
        return 0;
    }

Output:

Constructor
Destructor

For static and global variables the destructor may get called (depending on the compiler implementation).

    class MyClass
    {
        public:

        // Constructor
        MyClass() { cout<< "Constructor" << endl; }

        // Destructor
        MyClass() { cout<< "Destructor" << endl; }
    };

    int main()
    {
        static MyClass obj; 

        // Using exit
        exit(0);
    }

Output:

Implementation Dependent 

This is because static & global variables are load time variables and are allocated memory in the data area (which is independent of function call) and not in the Activation Record of a function.

Load time variables are cleaned up by the start-up library.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)