Click here to Skip to main content
15,886,518 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

The goto-less goto!

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
9 Feb 2011CPOL 6.3K   2  
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)


Written By
Technical Lead private interest
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --