如何在C中的宏内使用switch语句? [英] How to use switch statement inside a macro in C?
问题描述
我想在C中的宏内使用switch语句。我有以下代码段:
I want to use switch statement inside a macro in C. I have the following code segment:
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); \
但是,这会引发错误消息,更具体地说:
But, this throws an error message, more specificially:
错误: switch之前的预期表达式
error: expected expression before ‘switch’
为什么会这样,以及在C中的宏内使用switch的正确方法是什么?
Why is this happening exactly, and what is the proper way to use switch inside a macro in C?
推荐答案
您不能 return
从宏,并期望它的行为像一个函数。宏代码实际上是在您的代码中扩展的,所以现在您有了一个switch / case& printf
的最后一个参数中的一堆 return
语句!
you cannot return
from a macro and expect that it behaves like a function. The macro code is expanded literally in your code, so now you have a switch/case & a bunch of return
statements in the last parameter of printf
!
此外,在这里使用宏没有优势,因为您没有使用令牌粘贴,字符串或其他宏,例如 __ FILE __
或 __ LINE __
(而不是使用它们的 THROW_ERROR
宏)。
Besides, there's no advantage to use a macro here since you're not using token pasting, stringing or other macros like __FILE__
or __LINE__
in it (as opposed to your THROW_ERROR
macro which uses them).
相反,定义 MESSAGE
(或更佳的消息: message
)函数:
Instead, define a MESSAGE
(or better: message
) function:
const char *message(int code)
{
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;
}
return "unknown error"; // just in case no code matches
}
并将其传递给 printf
顺便说一句,将 THROW_ERROR
宏用大括号括起来,因为是2条语句:
As an aside, wrap your THROW_ERROR
macro within braces since there are 2 statements:
#define THROW_ERROR(err) do { \
fprintf(stderr, "Error in %s:%d: %s.\n", __FILE__, __LINE__, message(err)); \
exit(EXIT_FAILURE); } while(0)
否则,如果您这样做:
if (fail_code) THROW_ERROR(12);
然后,仅在 fprintf
语句执行时发生错误,无论发生什么事情退出
!
then only the fprintf
statement is executed when an error occurs, and exit
happens no matter what!
这篇关于如何在C中的宏内使用switch语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!