3 ms·
I can't imagine a clearer way of treating errors in C than the macros from Zed Shaw, which use goto (http://c.learncodethehardway.org/book/learn-c-the-hard-wayc
by swah 15y ago
I can't imagine a clearer way of treating errors in C than the macros from Zed Shaw, which use goto (http://c.learncodethehardway.org/book/learn-c-the-hard-waych21.html http://c.learncodethehardway.org/book/learn-c-the-hard-waych...):
int test_check(char *file_name)
34 {
35 FILE *input = NULL;
36 char *block = NULL;
37
38 block = malloc(100);
39 check_mem(block); // should work
40
41 input = fopen(file_name,"r");
42 check(input, "Failed to open %s.", file_name);
43
44 free(block);
45 fclose(input);
46 return 0;
47
48 error:
49 if(block) free(block);
50 if(input) fclose(input);
51 return -1;
52 }
- haberman 15y agoYes, the Linux kernel has used this error handling strategy for a long time (http://kerneltrap.org/node/553/2131 http://kerneltrap.org/node/553/2131). A variant on this is to have multiple error labels so that you uninitialize the correct set of things without the if statements (which may not be possible in cases where the resource is represented by an opaque handle).