Reputation: 43569
I know it's a simple question, but I'm looking to get my C++ groove on. I would imagine some sort of abort
function could be used. But I don't think that'll return any text like die('hello');
would.
Upvotes: 2
Views: 9816
Reputation: 15847
Assuming you need these equivalents for debugging purpose...
instead of die() you may invoke the debugger;
instead of var_export() you may inspect your variables content with the debugger.
Upvotes: -1
Reputation: 545875
I wouldn’t recommend calling std::abort
, std::exit
or anything like that.
It’s brute-force, and the semantics for proper cleanup are very complicated. You are essentially leaving (at least parts of) your program behind in a very messy state.
A much better way in C++ is to throw an exception which you then catch in main
:
#include <stdexcept>
struct fatal_error : std::logic_error {
fatal_error(char const* message) : std::logic_error(message) { }
};
int main() try {
… the normal program flow starts here
} catch (fatal_error const& e) {
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
Then, instead of die
, you’d simply say throw fatal_error("Something went wrong.");
.
Upvotes: 1
Reputation: 129454
There is no "print a message, then exit" in C or C++. You can quite easily write your own function for die
(or panic
, as I prefer to call it), something like:
void die(const std::string& msg)
{
std::cerr << msg << std::endl;
exit(1);
}
Or, if you want to avoid the problems with creating a string, which may fail under low memory conditons:
void die(const char *msg)
...
(the rest should be the same as above). The drawback here is that you can't trivially concatenate strings, e.g. die(std::string("Could not open file ") + filename);
won't work with const char *
.
A function that does var_dump
is much harder, as there is no direct way to actually fetch the content of a variable of a an arbitrary type, or an array, in C++. You could perhaps do something like this:
template<typename T>
void var_dump(const T& var)
{
std::cout << var << endl;
}
template<typename T, size_t N>
void var_dump(const T (&var)[N])
{
for(i : var)
{
std::cout << i << endl;
}
}
The latter is a bit like this PHP code: foreach($var as $i) echo $i . "\n";
. And I may have the syntax slightly wrong, not sure.
Upvotes: 7