-1 c c++ variables c-preprocessor
如何使用#define在数组中定义多个相同类型的值?
例如,我想
#define DIGIT 0x30 | 0x31 | 0x32 | 0x33 | 0x34 | 0x35 | 0x36 | 0x37 | 0x38 | 0x39
#define QUOTE 0x22 | 0x27
ETC...
Run Code Online (Sandbox Code Playgroud)
如何使用#define在数组中定义多个相同类型的值?例如,我想
#define DIGIT 0x30 | 0x31 | 0x32 | 0x33 | 0x34 | 0x35 | 0x36 | 0x37 | 0x38 | 0x39
#define QUOTE 0x22 | 0x27
Run Code Online (Sandbox Code Playgroud)
好吧,C和C++中的术语数组是指许多相同类型的变量,并且在内存中并排.如果你真的想要一个数组,那么你可以使用:
static const char digits[] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39
};
Run Code Online (Sandbox Code Playgroud)
当然,没有什么可以阻止你将其中的一部分放在预处理器宏中,但也没有明显的要点,并且最好避免使用宏,因为编译器并不总能很好地处理冲突和非预期的替换:
#define DIGITS 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39
static const char digits[] = { DIGITS };
Run Code Online (Sandbox Code Playgroud)
如果您想要检查特定字符是否是列出的字符之一,那么您可以通过多种方式执行此操作:
if (isdigit(c)) ... // use a library function
static const char digits[] = {
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0
};
if (strchr(digits, c)) ... // use another library function (probably slower)
static const char digits[] = "0123456789"; // exactly the same as above!
if (strchr(digits, c)) ...
if (c == 0x30 || c == 0x31 || c == 0x32 ...) ... // painfully verbose!
if (c == '0' || c == '1' || c == '2' ...) ... // verbose but self-documenting
if (c >= '0' && c <= '9') // as per caf's comment, C requires the
// character set to have contiguous numbers
Run Code Online (Sandbox Code Playgroud)