开发者

How do I #define multiple values C / C++

How would I define multiple values of the same type in an array using #define ?

For instance, I would like

#define DIGIT 0x30 | 0x31 | 0x开发者_如何学编程32 | 0x33 | 0x34 | 0x35 | 0x36 | 0x37 | 0x38 | 0x39
#define QUOTE 0x22 | 0x27

ETC...


How would I define multiple values of the same type in an array using #define ? For instance, I would like

#define DIGIT 0x30 | 0x31 | 0x32 | 0x33 | 0x34 | 0x35 | 0x36 | 0x37 | 0x38 | 0x39
#define QUOTE 0x22 | 0x27

Well, the term array in C and C++ refers to a number of variables of the same type, all side by side in memory. If you really wanted an array, then you can use:

static const char digits[] = {
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39
};

Of course, there's nothing to stop you putting part of this in a preprocessor macro, but no obvious point either, and macros are best avoided as conflicting and unintended substitutions aren't always handled well by the compiler:

#define DIGITS 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39
static const char digits[] = { DIGITS };

If your intension it to check whether a particular character is one of the listed characters, then you can do it in many ways:

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


You don't, you use an enum or an array.

typedef enum
{
    Zero  = 0x30,
    One   = 0x31,
    Two   = 0x32,
    Three = 0x33,
    /* etc. */
} digits;

The #define in your example is simply the result of all those bitwise OR operations.

To solve this using an array (as it would actually work well considering the indices would line up with the digits), well... just declare one! =)

You don't need to (and likely don't want to) use the preprocessor for that. Just declare a static const array:

static const char digits[] = { 0x30, 0x31, 0x32 /* etc */ };

int main(...) {
    char zero = digits[0];
    char one  = digits[1];
    char two  = digits[2];
}


You might want to consider using an enum to specify these values, and using well known functions, such as isdigit(int) (ctype.h).

Not sure of a standard C method for quotes (one probably exists though), but ORing those values together is probably not what you want anyway.


You don't. You use static const variables. Sorry to be pendantic, but stay away from the preprocessor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜