开发者

How do I do different things per macro value?

#define TYPE char *

if TYPE is char *
  do A
if TYPE is int
  do B
开发者_Python百科

Is there an example how to do such things?


C preprocessor MACROS manipulate text, so are essentially typeless, so NO you can't do that.


You could associate another symbol with it:

#define TYPE char *
#define TYPE_IS_CHAR_STAR

#ifdef TYPE_IS_CHAR_STAR
...
#endif

You just need to keep them consistent manually.

Note that that's a dangerous macro; you should use a typedef instead. With the macro:

TYPE x, y;

x is a pointer, but y isn't.


You can get a similar effect by defining another macro along with the type, and using #ifdef etc. with that other macro. For example:

#define TYPE char *
#define TYPE_IS_PCHAR 1

...then later...

#ifdef TYPE_IS_PCHAR
   do A
#endif
#ifdef TYPE_IS_INT
   do B
#endif

It's not quite the same thing, but it still gets you there.


Not easily. You could do something like:

#define TYPE_IS_CHARPTR
//#define TYPE_IS_INT

#ifdef TYPE_IS_CHARPTR
    do A
#endif
#ifdef TYPE_IS_INT
    do B
#endif

But you really should be trying to minimise your use of the preprocessor for tricky things (anything other than simple variables).

With enumerated constants and inline functions, there's little need for such uses nowadays.


It would work if you just used basic types (since they're just strings - see Mitch's answer). But as soon as you try to use pointers, it won't work any more - the asterisk throws the preprocessor for a loop:

[holt@Michaela ~]$ gcc test.c
test.c:3:10: error: operator '*' has no right operand

But if you want do do different things based on different types, I'm going to have to recommend switching to C++ and using templates and template specialization. Reluctantly, since template syntax is incredibly ugly, but you should be able to do whatever you want.

Hope that helps!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜