懒人用宏替换大量case语句的方法

来源:互联网 发布:太原手机数据恢复 编辑:程序博客网 时间:2024/06/06 00:48
比较懒,又不想代码失去基本的优雅,于是写了这么一个玩意儿。

  1. #define MESSAGE_FUNCTION_BEGIN(x) switch(x) { 
  2. #define MESSAGE_FUNCTION(x,y) case x: { y(x); break; }
  3. #define MESSAGE_FUNCTION_END }

  4. void Do_1(int x)
  5. {
  6.         printf("[Do_1]x=%d.\n", x);
  7. }

  8. void Do_2(int x)
  9. {
  10.         printf("[Do_2]x=%d.\n", x);
  11. }

  12. void Do_3(int x)
  13. {
  14.         printf("[Do_3]x=%d.\n", x);
  15. }

  16. void RegFunction(int x)
  17. {
  18.         MESSAGE_FUNCTION_BEGIN(x);
  19.         MESSAGE_FUNCTION(1, Do_1);
  20.         MESSAGE_FUNCTION(2, Do_2);
  21.         MESSAGE_FUNCTION(3, Do_3);
  22.         MESSAGE_FUNCTION_END;
  23. }
复制代码

嘿嘿,测试一下。
  1.         RegFunction(1);
  2.         RegFunction(2);
  3.         RegFunction(3);
复制代码

输出
[Do_1]x=1.
[Do_2]x=2.
[Do_3]x=3.


OK,懒惰成功!
0 0
原创粉丝点击