Clean ways to do multiple undo in C?

  • A+
Category:Languages

Someone will probably say something about exceptions... but in C, what are other ways to do the following cleanly/clearly and without repeating so much code ?

if (Do1()) { printf("Failed 1"); return 1; } if (Do2()) { Undo1(); printf("Failed 2"); return 2; } if (Do3()) { Undo2(); Undo1(); printf("Failed 3"); return 3; } if (Do4()) { Undo3(); Undo2(); Undo1(); printf("Failed 4"); return 4; } if (Do5()) { Undo4(); Undo3(); Undo2(); Undo1(); printf("Failed 5"); return 5; } Etc... 

This might be one case for using gotos. Or maybe multiple inner functions...

 


There are probably many ways to do this, but one idea is since you won't call one function unless the preceeding one succeeded, you could chain your function calls using else if like this. And using a variable to track where it fails you can use a switch statement to roll back easily too.

int ret=0; if(Do1()) {     ret=1; } else if(Do2()) {     ret=2; } else if(Do3()) {     ret=3; } else if(Do4()) {     ret=4; } else if(Do5()) {     ret=5; }  if(ret) {     printf("Failed %d/n",ret);     switch(ret) {            case 5:               Undo5();         case 4:               Undo4();         case 3:               Undo3();         case 2:               Undo2();         case 1:             Undo1();         break;      } } return ret; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: