The clever use of do... while (0) in C language-avoid goto
Use goto elegance and avoid structure confusion
Use do {…} to jump to the statement {...} Pack while (0.
Reference
# Defien N 10 bool Execute () {// allocate resource int * p = (int *) malloc (N * sizeof (int); bool bOk = true; // execute and handle errors bOk = func1 (); if (! BOk) {free (p); p = NULL; return false;} bOk = func2 (); if (! BOk) {free (p); p = NULL; return false;} bOk = func3 (); if (! BOk) {free (p); p = NULL; return false ;}//.......... // The execution is successful. Release the resource and return free (p); p = NULL; return true ;}
# Defien N 10 bool Execute () {// allocate resource int * p = (int *) malloc (N * sizeof (int); bool bOk = true; // execute and handle errors bOk = func1 (); if (! BOk) goto errorhandle; bOk = func2 (); if (! BOk) goto errorhandle; bOk = func3 (); if (! BOk) goto errorhandle ;//.......... // The execution is successful. Release the resource and return free (p); p = NULL; return true; errorhandle: free (p); p = NULL; return false ;}
# Defien N 10 bool Execute () {// allocate resource int * p = (int *) malloc (N * sizeof (int); bool bOK = true; do {// execute and handle errors bOK = fun1 (); if (! BOK) break; bOK = fun2 (); if (! BOK) break; bOK = fun3 (); if (! BOK) break; //...} while (0); // release the resource free (p); p = NULL; return bOK ;}