How to End C++ Code
I Would Like My C++ Code to Stop Running If a Certain Condition Is Met, but I'm Not Sure How to Do That. So Just at Any Point If an If Statement Is True...
I would like my C++ code to stop running if a certain condition is met, but I'm not sure how to do that. So just at any point if an if statement is true terminate the code like this:
if (x==1)
{
kill code;
}
14 Answers
There are several ways, but first you need to understand why object cleanup is important, and hence the reason std::exit is marginalized among C++ programmers.
Must Read
RAII and Stack Unwinding
C++ makes use of a idiom called RAII, which in simple terms means objects should perform initialization in the constructor and cleanup in the destructor. For instance the std::ofstream class [may] open the file during the constructor, then the user performs output operations on it, and finally at the end of its life cycle, usually determined by its scope, the destructor is called that essentially closes the file and flushes any written content into the disk.
What happens if you don't get to the destructor to flush and close the file? Who knows! But possibly it won't write all the data it was supposed to write into the file.
For instance consider this code
#include <fstream>
#include <exception>
#include <memory>
void inner_mad()
{
throw std::exception();
}
void mad()
{
auto ptr = std::make_unique<int>();
inner_mad();
}
int main()
{
std::ofstream os("file.txt");
os << "Content!!!";
int possibility = /* either 1, 2, 3 or 4 */;
if(possibility == 1)
return 0;
else if(possibility == 2)
throw std::exception();
else if(possibility == 3)
mad();
else if(possibility == 4)
exit(0);
}
What happens in each possibility is:
- Possibility 1: Return essentially leaves the current function scope, so it knows about the end of the life cycle of
osthus calling its destructor and doing proper cleanup by closing and flushing the file to disk. - Possibility 2: Throwing a exception also takes care of the life cycle of the objects in the current scope, thus doing proper cleanup...
- Possibility 3: Here stack unwinding enters in action! Even though the exception is thrown at
inner_mad, the unwinder will go though the stack ofmadandmainto perform proper cleanup, all the objects are going to be destructed properly, includingptrandos. - Possibility 4: Well, here?
exitis a C function and it's not aware nor compatible with the C++ idioms. It does not perform cleanup on your objects, includingosin the very same scope. So your file won't be closed properly and for this reason the content might never get written into it! - Other Possibilities: It'll just leave main scope, by performing a implicit
return 0and thus having the same effect as possibility 1, i.e. proper cleanup.
But don't be so certain about what I just told you (mainly possibilities 2 and 3); continue reading and we'll find out how to perform a proper exception based cleanup.