Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a C++ console program exit?

Tags:

c++

exit

Is there a line of code that will terminate the program?

Something like python's sys.exit()?

like image 634
rectangletangle Avatar asked Oct 27 '10 22:10

rectangletangle


2 Answers

While you can call exit() (and may need to do so if your application encounters some fatal error), the cleanest way to exit a program is to return from main():

int main() {     // do whatever your program does  } // function returns and exits program 

When you call exit(), objects with automatic storage duration (local variables) are not destroyed before the program terminates, so you don't get proper cleanup. Those objects might need to clean up any resources they own, persist any pending state changes, terminate any running threads, or perform other actions in order for the program to terminate cleanly.

like image 124
James McNellis Avatar answered Oct 22 '22 14:10

James McNellis


#include <cstdlib> ... exit( exit_code ); 
like image 33
Benjamin Lindley Avatar answered Oct 22 '22 15:10

Benjamin Lindley