Sometimes, when developing these “fancy” things are required. If we can break an if
, a lot of nested if
s won’t be necessary, making the code much more clean and aesthetic.
This sample code illustrates that in certain situations a breaked if
can be much more suitable than a lot of ugly nested if
s.
Ugly code
if(process_x()) {
/* do a lot of other things */
if(process_y()) {
/* do a lot of other things */
if(process_z()) {
/* do a lot of other things */
/* SUCCESS */
}
else {
clean_all_processes();
}
}
else {
clean_all_processes();
}
}
else {
clean_all_processes();
}
Good looking code
do {
if( !process_x() )
{ clean_all_processes(); break; }
/* do a lot of other things */
if( !process_y() )
{ clean_all_processes(); break; }
/* do a lot of other things */
if( !process_z() )
{ clean_all_processes(); break; }
/* do a lot of other things */
/* SUCCESS */
} while (0);
As @NiematojakTomasz says, the use of goto
is an alternative, the bad thing about this is you always need to define the label (point target).