C Preprocessor Interview Questions

C Preprocessor Interview Questions
1.How can I write a generic macro to swap two values?
A:There is no good answer to this question. The best all-around
solution is probably to forget about using a macro.

2.I have some old code that tries to construct identifiers with a
macro like “#define Paste(a, b) a/**/b”, but it doesn’t work any
more.

A:Try the ANSI token-pasting operator ##.

3.What’s the best way to write a multi-statement cpp macro?
A: #define Func() do {stmt1; stmt2; … } while(0) /* (no trailing ; ) */

4.How can I write a cpp macro which takes a variable number of
arguments?

A:One popular trick is to define the macro with a single argument,
and call it with a double set of parentheses, which appear to the
preprocessor to indicate a single argument:

#define DEBUG(args) {printf(“DEBUG: “); printf args;}
if(n != 0) DEBUG((“n is %d\n”, n));

No comments: