Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

The goto-less goto!

, 31 Jan 2011
Rate this:
Please Sign up or sign in to vote.
For Cbool bFailed = true;// foreverfor(;;) { // do something here. if(condition1) { // exit the loop (goto) break; } // do something here. // .... // In case you want to goto to the top instead of exit. if(condition2) { // jump to top of the...
For C
bool bFailed = true;
 
// forever
for(;;) {
  // do something here.

  if(condition1) {
    // exit the loop (goto)
    break;
  }
 
  // do something here.
  // ....

  // In case you want to goto to the top instead of exit.
  if(condition2) {
    // jump to top of the loop. (goto)
    continue;
  }
 
  // Success.
  bFailed = false;
  // This break is necessary to avoid an infinite loop.
  break;
} // forever

if(bFailed) {
  // do your error cleanup here. 
}
 
// do your unconditional cleanup here.
 
For C++
bool bFailed = true;
 
// In case of an exception.
try {
  // forever
  for(;;) {
    // do something here.
  
    if(condition1) {
      // exit the loop (goto)
      break;
    }
  
    // do something here.
    // ....
  
    // In case you want to goto to the top instead of exit.
    if(condition2) {
      // jump to top of the loop. (goto)
      continue;
    }
  
    // Success.
    bFailed = false;
    // This break is necessary to avoid an infinite loop.
    break;
  } // forever
} catch(...) {
  // this assumes you want to catch all.
}
 
if(bFailed) {
  // do your error cleanup here. 
}
 
// do your unconditional cleanup here.

License

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

About the Author

rxantos

United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 31 Jan 2011
Article Copyright 2011 by rxantos
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid