C's Limited Macro Capabilities

I PROMISED I would only say nice things! david at sun.com
Wed Dec 6 06:28:33 AEST 1989


In article <69517 at psuecl.bitnet> bpm at psuecl.bitnet (Brian Moquin) writes:
>A student in my C class asked me an interesting question:  can you have
>conditional compilation directives embedded within '#define' macros?
>The answer is no.  The student pointed out that this then
>severely limits the macro capabilities of C.  He said that in assembler
>(MASM, I'm sure), he can write macros which contain arguments that
>determine how the macros get expanded.  I had trouble coming up with
>a good analogous example in C, but here's one to think about:
>        #define cast(flag,x)    #if flag=='I' \
>                                        ((int)(x)) \
>                                #elif flag=='F' \
>                                        ((float)(x)) \
>                                #endif

In (Reiser) cpp you can accomplish this sort of thing with token pasting
and a few additional macros:

#define	_CAT(a,b)	a/**/b
#define	cast(flag,x)	_CAT(_CAST,flag)(x)
#define	_CASTI(x)	((int) (x))
#define	_CASTF(x)	((float) (x))

cast(I, foo)
cast(F, bar)

-- 
David DiGiacomo, Sun Microsystems, Mt. View, CA  sun!david david at eng.sun.com



More information about the Comp.lang.c mailing list