A multi-dimensional array is very useful in c language. We can replace the nested switch case with multidimensional array using the pointer to function. Using this technique, a function which has a hundred lines of code reduced dramatically.

Previously I have worked on a POS (point of sale) application, in this application we have used a lot of nested switch case.Application has a main screen where all type of transaction (SALE, VOID REFUND … etc) display. In the application, we have categorized all transaction on the basis of screen state and every main screen state has a sub screen states.

In this article, I am creating a pseudo program code to describe, how we can replace a nested switch case with a multi-dimensional array.

Suppose there is an application which has different transaction methods and transaction method is identified by the different screen states. In below demo program transaction methods are identified by the MenuStates.

Further, every Menu state consists another sub states.Every Menu state should have the unique sub state.

Note: In this application important point is that we have nested switch statement and the number of substates is different for each menu states.

In below example, I am creating a sample program to describe the working of nested switch case.

nested switch c++

In the above program nested switch case statement execute on the basis of Menustate and substate value.Nested switch case increase the length of the program.Some times its hard to modify the nested switch case due to their length.

Steps to replace nested switch cases with a multidimensional array of pointer to function:
  • First, need to create an array of pointer to function.In my case, only one nested switch so here I am creating a 2D array of pointer to function.
  • Assign the address of function at the proper index of the array.
  • Put the NULL or dummy function at the empty index of the array.
  • Always check the boundary of the array before calling the function.
  • We need to check NULL before calling the function either we will get the segmentation fault.

nested switch

In above program, nested switch case replace by an array of pointer to function.
Sometimes this approach creates the issues and reduces the readability of the code.
So it totally depends on your requirement and design of the application that replacing the nested switch case with the multidimensional array is the benefit or not.