Clean ways to do multiple undos 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...

 


Yes, it's quite common to use goto in such cases to avoid repeating yourself.

An example:

int hello() {   int result;    if (Do1()) { result = 1; goto err_one; }   if (Do2()) { result = 2; goto err_two; }   if (Do3()) { result = 3; goto err_three; }   if (Do4()) { result = 4; goto err_four; }   if (Do5()) { result = 5; goto err_five; }    // Assuming you'd like to return 0 on success.   return 0;  err_five:   Undo4(); err_four:   Undo3(); err_three:   Undo2(); err_two:   Undo1(); err_one:   printf("Failed %i", result);    return result; } 

As always you probably also want to keep your functions small and batch together the operations in a meaningful manner to avoid a large "undo-code".

Comment

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