65.9K
CodeProject is changing. Read more.
Home

The goto-less goto!

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Feb 9, 2011

CPOL
viewsIcon

6411

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 

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;
}