Is goto to improve DRY-ness OK?
- by Marco Scannadinari
My code has many checks to detect errors in various cases (many conditions would result in the same error), inside a function returning an error struct. Instead of looking like this:
err_struct myfunc(...) {
err_struct error = { .error = false };
...
if(something) {
error.error = true;
error.description = "invalid input";
return error;
}
...
case 1024:
error.error = true;
error.description = "invalid input"; // same error, but different detection scenario
return error;
break; // don't comment on this break please (EDIT: pun unintended)
...
Is use of goto in the following context considered better than the previous example?
err_struct myfunc(...) {
err_struct error = { .error = false };
...
if(something) goto invalid_input;
...
case 1024:
goto invalid_input;
break;
return error;
invalid_input:
error.error = true;
error.description = "invalid input";
return error;