What is the best way to manage resources for a C program. Should I use a nested if structure or should I use goto statements?
I am aware there is a lot
That's my philosophy.
Seriously, on some occasions a goto
is reasonable, especially if it just does something obvious like jump to common return code at the bottom of a function.
If by using goto
you can avoid writing complex code, then use goto
.
Your example could also be written like this (no goto
s):
void anotherExample()
{
char *string1, *string2, *string3, *string4, *string5;
string1 = string2 = string3 = string4 = string5 = 0;
if ((string1 = (char*) calloc(STRING_MAX, sizeof(char)))
&& (string2 = (char*) calloc(STRING_MAX, sizeof(char)))
&& (string3 = (char*) calloc(STRING_MAX, sizeof(char)))
&& (string4 = (char*) calloc(STRING_MAX, sizeof(char)))
&& (string5 = (char*) calloc(STRING_MAX, sizeof(char))))
{
//important code here
}
free(string1);
free(string2);
free(string3);
free(string4);
free(string5);
}
Personally I have used goto in this manner in the past. People hate it because it reminds them of the spaghetti code they used to write/maintain, or because someone who wrote/maintaned such code beat the concept that gotos are evil into them.
You probably could write something decent without goto, sure. But it's not going to do any harm in this kind of circumstance.
Cleanup using goto
has the advantage that it's less error-prone. Having to free each and every resource allocated on each and every return point can lead to someone someday missing some cleanup when doing maintenance work.
That said, I'll quote Knuth's "Structured Programming with goto Statements":
I argue for the elimination of go to's in certain cases, and for their introduction in others.
and Knuth's quote of Dijkstra in that same paper:
"Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline!" [29].
No doubt about it Dijkstra was a formidable personality in the programming world. His Goto Considered Harmful paper was way overblown. Yes GoTo may be used indiscriminately and can be harmfull but many think an outright ban on GoTo is not warranted. Knuth provided a very well reasoned rebuttal to Dijkstra in: Structured Programming with GO TOs
Read Knuth's paper, you will find that your GoTo pattern is one of the good uses for GoTo.
BTW, Dijkstra is very quotable for a number of other things too. How about:
Dijkstra was a great mathematician and made huge contributions to computer science. However, I don't think he had to deal with, or was interested in, the day to day type stuff that 99.99 percent of our programs do.
Use GoTo only with reason and structure. Use them rarely. But do use them.