How to avoid writing a switch too long?

There is a lot of code in my current project using switch with too many cases.

Switch(c)
{
case CASENUMBERONE:
//50-100 lines of code in each code
...
case CASENUMBERTWENTY:
..
}


//thousands of lines of macro definition in another file
#define CASENUMBERONE 1
...
#define CASENUMBERTWENTY 20
...

This does not seem to be a reasonable programming style. How to avoid this?

+3
source share
9 answers

It depends.

  • You can write a function for each case. You can embed them if you are concerned about performance, but in real life, in fact, you can get a performance boost due to the presence of separate functions due to better consistency of the command cache.

  • , . , /, . - , - . , NULL.

  • .

+16

@Zain, / ( , ).

, , , .

handler[c](): -)

, , .

, ( switch).

hth.,

+4

, . , , , , . "" , . , , , , . .

, .

+2

1500 = (50-100 ) * 20

. .

/ .

/, , . ( )

( )

+2

, .

+1

, . , , , ; , , .

, - , , ; .

++ :/

+1

, , ,

0

, . boost:: assign:: map_list_of.

find . , .

0

- :

, case foo , . , , . , , .

, , ptr- > foo (c) ptr- > foo(). , .

0

Source: https://habr.com/ru/post/1771243/


All Articles