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. Commented Nov 21, 2018 at 14:07
  • 1
    OK I deleted it on SO and update my question here as well. Thanks. Commented Nov 21, 2018 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? Commented Nov 29, 2018 at 13:42
  • no that is why the array solution may not apply to my case Commented Nov 29, 2018 at 13:56

2 Answers 2


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[]

foreach (var index = step-1; index <= function.count; index++)
  • Thanks, currently I am using javascript but I think your solution applies to c/c++ too. Thanks! Commented Nov 21, 2018 at 14:24
  • This would be the ideal solution, as long as the input and output of each function is the same. Commented Nov 29, 2018 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 agree to our terms of service and acknowledge you have read our privacy policy.

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