Click here to Skip to main content
15,881,204 members
Articles / Programming Languages / C#
Tip/Trick

The goto-less goto!

Rate me:
Please Sign up or sign in to vote.
3.34/5 (23 votes)
24 Jan 2011CPOL 82.2K   9   26
The goto-less goto!
You have non-looped, sequenced code, like below:

  bool bFailed = true;
  if(condition1_fails)
     goto Exit;
  ...
  if(condition2_fails)
     goto Exit;
  ...
  ...
  if(conditionN_fails)
     goto Exit;

  bFailed=false;
  PerformActionOnAllSuccess();

Exit:
  if(bFailed)
     DoFailedCleanup();
  else
     DoNormalCleanup()

Here is the goto-less goto, that you can use:
bool bFailed=true;
do
{
  if(condition1_fails)
     break;
  ...
  if(condition2_fails)
     break;
  ...
  ...
  if(conditionN_fails)
     break;

   bFailed = false;
   PerformActionOnAllSuccess();

 } while(false); // Ignore or disable warning at function-level

 if(bFailed)
    DoFailedCleanup();
 else
    DoNormalCleanup();

It runs a do-while loop, which would run only once. As soon as some failed-condition encounters, it exits (break) from loop.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Started programming with GwBasic back in 1996 (Those lovely days!). Found the hidden talent!

Touched COBOL and Quick Basic for a while.

Finally learned C and C++ entirely on my own, and fell in love with C++, still in love! Began with Turbo C 2.0/3.0, then to VC6 for 4 years! Finally on VC2008/2010.

I enjoy programming, mostly the system programming, but the UI is always on top of MFC! Quite experienced on other environments and platforms, but I prefer Visual C++. Zeal to learn, and to share!

Comments and Discussions

 
GeneralRe: Fine but..... Pin
Ajay Vijayvargiya23-Apr-10 22:35
Ajay Vijayvargiya23-Apr-10 22:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.