Tag Archives: dijkstra

Go To Statement Considered Harmful (discussed)

Talking with other developers about control-flow patterns, after a while someone will cite Edgar Dijkstra’s paper

“Go To Statement Considered Harmful” Communications of the ACM 11, 3 (March 1968), pages 147-148

Usually those developers argue, that go to statements should be abolished completely.

Just, it is important to note, that this paper is about loop-control-structures, comparing the expressiveness of recursive function calls, while/repeat-statements and goto-statements with each other (preferred pattern mentioned first).

And Dijkstra does not oppose the usage of go to statements in general, but mentioning a use case for go to statements:

“The remark about the undesirability of the go to statement is far from new. I remember having read the explicit recommendation to restrict the use of the go to statement to alarm exits, but I have not been able to trace it; presumably, it has been made by C.A.R. Hoare.”

My interpretation of this statement is, that go to statements can be tolerated for so called “alarm exits” as being used widely in C-code of OS-Kernels and embedded systems.

An “alarm exit” may look like this, realizing a single exit point for the success case and a single one for the error case, instead of spreading multiple exit-points all over the function.

/**  foo reading a file and returns with SUCCESS, otherwise with ERROR
*/
int foo(const char* filename) {
int fd = INVALID_FD;
if (filename==INVALID_STRING) {
goto alarm_exit;
}
fd = open_file(filename);
if (fd == INVALID_FD) {
goto alarm_exit;
}
/* do something, release resource and exit with success */
close_file(fd);
return SUCCESS_CASE;

alarm_exit:
/* release resources if allocated */
if (fd!=INVALID_FD) close_file(fd);
return ERROR_CASE;
}

So, next time having a discussion with fundamental developers, abolishing all occurances of go to statements (even for the “alarm exits” use case), I will be happy to cite Dijkstra and Hoare 😉