- #36
nsaspook
Science Advisor
- 1,369
- 4,014
newjerseyrunner said:Outside of C, you should never use goto, you should use scope to clean up:
Bad code
Code:FILE * fp1 = fopen("/tmp/test.txt", 'w'); if (!fp1) goto error1; FILE * fp2 = fopen("tmp/test2.txt", 'w'); if (!fp2) goto error2; error2: fclose(fp1); error1: return;
Good code
Code:struct file_cleanup { file_cleanup(FILE * fp) : myfp(fp){} ~file_cleanup(){ if (myfp) fclose(myfp); } FILE * myfp; }; file_cleanup fp1(fopen("/tmp/test.txt", 'w')); if (!fp1.myfp) return; file_cleanup fp2(fopen("/tmp/test.txt", 'w')); if (!fp2.myfp) return; //fp1 is automatically cleaned up
Baloney. I agree your goto example is bad 'need to use goto' code, mine is not in the correct context (C device driver).
http://koblents.com/Ches/Links/Month-Mar-2013/20-Using-Goto-in-Linux-Kernel-Code/
http://eli.thegreenplace.net/2009/04/27/using-goto-for-error-handling-in-c
http://c.learncodethehardway.org/book/
Last edited: