Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

The goto-less goto!

3.34/5 (23 votes)
24 Jan 2011CPOL 1  
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)