【发布时间】:2018-09-08 20:51:36
【问题描述】:
我想在 C 中的宏中使用 switch 语句。我有以下代码段:
enum errors {
ERROR_NO_MEMORY,
ERROR_INVALID_INDEX,
ERROR_INVALID_VALUE
};
#define MSG_NO_MEMORY "could not allocate memory"
#define MSG_INVALID_INDEX "index out of bounds"
#define MSG_INVALID_VALUE "invalid value passed as input"
#define MESSAGE(err) \
switch (err) { \
case ERROR_NO_MEMORY: \
return MSG_NO_MEMORY; \
case ERROR_INVALID_INDEX: \
return MSG_INVALID_INDEX; \
case ERROR_INVALID_VALUE: \
return MSG_INVALID_VALUE; \
} \
#define THROW_ERROR(err) \
fprintf(stderr, "Error in %s:%d: %s.\n", __FILE__, __LINE__, MESSAGE(err)); \
exit(EXIT_FAILURE); \
但是,这会引发错误消息,更具体地说:
错误:“switch”之前的预期表达式
为什么会发生这种情况,以及在 C 中的宏中使用 switch 的正确方法是什么?
【问题讨论】:
-
这个宏怎么用?
-
@tkausl 请检查已编辑的问题。
-
宏以`\`结尾:不好
-
您不能像使用函数一样使用宏。请改用函数。
-
如果一个函数可以完成这项工作,就不要使用宏。这里没有理由使用宏。这显然是一个 XY 问题。
标签: c switch-statement c-preprocessor