0

In a C program, within the main function, is there a difference between

exit(1);

and

return 1;

?

zell
  • 9,830
  • 10
  • 62
  • 115
  • 1
    Does this answer your question? [What is the difference between exit and return?](https://stackoverflow.com/questions/3463551/what-is-the-difference-between-exit-and-return) – alagner Apr 20 '22 at 00:13
  • From the `main()` function, no. But from any other function, yes. – Pablo Apr 20 '22 at 00:17

1 Answers1

-1

exit represents immediate termination which will terminate program.

In the below program when we return value from main the destructors will be called but not in case when we use exit(value).

#include <iostream>
#include<string.h>

using namespace std;

class String {
private:
    char* s;
    int size;
 
public:
    String(char*); // constructor
    ~String(); // destructor
};
 
String::String(char* c){
    cout<<"Calling constructor"<<endl;
    size = strlen(c);
    s = new char[size + 1];
    strcpy(s, c);
}
String::~String() {
    cout<<"Calling destructor"<<endl;
        delete[] s; 
}

int main(){
    String s("Hell o");

    exit(1);
    //return 1;
}
Udesh
  • 2,415
  • 2
  • 22
  • 32
  • 4
    While highly educational for C++ programmers, the OP was asking about, and likewise tagged for, C, not C++. – WhozCraig Apr 20 '22 at 00:26