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

The goto-less goto!

5.00/5 (1 vote)
9 Feb 2011CPOL 6.4K  
If you really have to put everything into a single function and want to keep the code analyzable and maybe want to be able put some common code at the end, you can always use a success variable. The code does not slow down, as the compiler optimizes the sequenced if-conditions away and produces...
If you really have to put everything into a single function and want to keep the code analyzable and maybe want to be able put some common code at the end, you can always use a success variable. The code does not slow down, as the compiler optimizes the sequenced if-conditions away and produces jumps to the end of the sequence (just checked on this in VS2008).

#include <iostream>

void Test( int aValue ) {
  bool  l_ok = true;

  std::cout << "starting Test " << aValue << std::endl;
  l_ok = aValue < 8;

  if (l_ok) {
    std::cout << "value < 8" << std::endl;
    l_ok = aValue > 5;
  }

  // add more cases here
  if (l_ok) {
    std::cout << "value > 5" << std::endl;
  }
  std::cout << "finishing Test success " << l_ok << std::endl;
}


int main( int argc, char * argv[] ) {
  int result = 0;
  int l_value;

  for (l_value = 0; l_value < 10; ++l_value) Test( l_value );
  return result;
}
</iostream>

License

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