Wednesday, February 16, 2011

C++

In C++, what is the difference between exit(0) and return 0 ?

2 comments:

  1. exit terminates the program while return returns the value at end of function.exit(0)means exits from the program if value return is true.return 0 returns 0 at the end of the function.

    ReplyDelete
  2. When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

    Example :

    Exit(0)
    #include
    #include
    #include

    using namespace std;

    class Test {
    public:
    Test() {
    printf("Inside Test's Constructor\n");
    }

    ~Test(){
    printf("Inside Test's Destructor");
    getchar();
    }
    };

    int main() {
    Test t1;

    // using exit(0) to exit from main
    exit(0);
    }


    Return(0)

    #include
    #include
    #include

    using namespace std;

    class Test {
    public:
    Test() {
    printf("Inside Test's Constructor\n");
    }

    ~Test(){
    printf("Inside Test's Destructor");
    }
    };

    int main() {
    Test t1;

    // using return 0 to exit from main
    return 0;
    }

    ReplyDelete