Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Abusing" loops for reducing if-nesting

Tags:

c++

Sometime one have to implement a series of if/else checks. In old-days goto was the sandard instrument for this.

As goto is a no-go in many code style guides, I sometimes use loops as a replacement e.g.:

do
{
  if (a)
  {
   doA();
   break;
  }
  //...
  if (z)
  {
   doZ();
   break;
  }
}while(false);

//all break jump here

Is it a good approach? Is there a good C++ pattern (e.g. using templates, inheritance, etc.) for implementing this without too much overhead?

like image 743
Valentin H Avatar asked Oct 26 '15 10:10

Valentin H


1 Answers

As conditions seem unrelated, else if is an option:

if (a) {
    doA();
} else if (b) {
//...
} else if (z) {
    doZ();
}
like image 158
Jarod42 Avatar answered Sep 20 '22 22:09

Jarod42