I am used to avoid goto
statement in all cost , because it is not adviced c++ ,
i still need sometimes to jump to the buttom of the code and exit the process when an error occur like this :
if ( cond1 )
{
if (cond2)
{
do_something();
return; // note the return
}else
{
goto error_oc;
}
}else
{
if() ...
return;
}
// should never be eached
error_oc:
error_message();
exit(1);
now suppose the error message is a complex one , and suppose we didnt put it in a function like that , so we will have to write the complex msg code twice , now a better solution :
std::function <void(void)> error_lambda = [] (int code) {
// complex error msg here with captured variiables maybe
exit(code);
}
if ( cond1 )
{
if (cond2)
{
do_something();
return; // note the return
}else
{
error_lambda(1);
}
}else
{
if() ...
return;
}
// should never be eached
error_lambda(2);
what are the pros and cons of the solution vs the goto
solution ?