My program needs to execute a sequence of steps from start to end. But based on different input the start point will vary, e.g, some will run from the first step to end, some will run from the 2nd step to the end, some will run from the 3rd to the end, etc.

I just need a simple design, currently I use fall-through switch like this:

switch (step) {
case 1:
     //do the 1st step
     //fall through, so no break here
case 2:
    //do the 2nd step
    //fall through
case 3:
    //do the 3rd step
    //fall through
...
}

It works but the fall through code always makes me uncomfortable. Is there a better and simple way to do it ?

  • 1
    You shouldn't crosspost. I believe your question makes sense on this website, so if I were you, I would delete the question on Stack Overflow. – Vincent Savard Nov 21 at 14:07
  • 1
    OK I deleted it on SO and update my question here as well. Thanks. – Qiulang Nov 21 at 14:08
  • Is the data required for each step the same? Can you extract each step into its own function with the same arguments and return type? – Greg Burghardt Nov 29 at 13:42
  • no that is why the array solution may not apply to my case – Qiulang Nov 29 at 13:56

Depending on the language you are using, you can create a array of functions and use step as your start point for looping over them. Something like:

var functions = function[]
{
    step1,
    step2,
    step3,
    …
}

foreach (var index = step-1; index <= function.count; index++)
{
    functions[index]();
}
  • Thanks, currently I am using javascript but I think your solution applies to c/c++ too. Thanks! – Qiulang Nov 21 at 14:24
  • This would be the ideal solution, as long as the input and output of each function is the same. – Greg Burghardt Nov 29 at 13:41

The way you are doing it is perfectly good and simple; it's what fallthrough is for in the first place. If it makes you more comfortable, you can add a comment explaining what you are doing (so that somebody else doesn't take half an hour to understand why it's that way).

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.