当前位置:文档之家› 如何用指向函数的指针替换switch-case

如何用指向函数的指针替换switch-case

程序中当switch-case里面有很多分支,且每个分支有很多操作要做时,会花费很多时间,优化的方法有很多,比如将可能性大的放在前
面,将case操作压缩,其实,最好的方法利用指向函数的指针解决问题,下面我们来看一个例子:

先来一个switch-case的模板:

view plaincopy to clipboardprint?
1. #include
2. #include
3.
4. enum MsgType{ Msg1=1 ,Msg2 ,Msg3 ,Msg4 };
5.
6. int menu()
7. {
8. int choice;
9. printf("1.ADD/n");
10. printf("2.DEL/n");
11. printf("3.SORT/n");
12. printf("4.exit/n");
13. printf("input your choice:/n");
14. scanf("%d",&choice);
15. return choice;
16. }
17.
18. void ADD()
19. {
20. NULL;
21. //
22. }
23.
24. void DEL()
25. {
26. NULL;
27. //
28. }
29.
30. void SORT()
31. {
32. NULL;
33. //
34. }
35.
36. int main()
37. {
38. while(1)
39. {
40. switch(menu())
41. {
42. case Msg1:
43. ADD();
44. break;
45. case Msg2:
46. DEL();
47. break;
48. case Msg3:
49. SORT();
50. break;
51. case Msg4:
52. exit(0);
53. break;
54. default:
55. printf("input error/n");
56. break;
57. }
58. }
59. return 0;
60. }
61.
62.

那我们怎样将这个switch-case的模板改成利用指向函数的指针解决的问题呢?答案就在下面:

view plaincopy to clipboardprint?
1. #include
2. #include
3.
4. void ADD();
5. void DEL();
6. void SORT();
7. void EXIT();
8.
9. void (*MsgFunc[])()={ ADD ,DEL ,SORT ,EXIT };
10.
11. int menu()
12. {
13. int choice;
14. printf("1.ADD/n");
15. printf("2.DEL/n");
16. printf("3.SORT/n");
17. printf("4.EXIT/n");
18. printf("input your choice:/n");
19. scanf("%d",&choice);
20. return choice-1;
21. }
22.
23. int main()
24. {
25. while(1)
26. {
27. MsgFunc[menu()]();
28. }
29. return 0;
30. }
31.
32. void ADD()
33. {
34. NULL;
35. //
36. }
37.
38. void DEL()
39. {
40. NULL;
41. //
42. }
43.
44. void SORT()
45. {
46. NULL;
47. //
48. }
49.
50. void EXIT()
51. {
52. exit(0);
53. }
54.
55.

这样,就用指向函数的指针解决了switch-case,且代码量也变少了,程序模块化也变清晰了。在编程中要充分利用这些知识来优化程
序。

相关主题