Nested macros

T

The D0ct0r

Hey,

please consider the following:

#if DEBUG
#define SOMEMACRO(type, name, value) (type) (name) = (value)
#else
#define SOMEMACRO(type, name, value) #define (name) (value)
#endif

If I define DEBUGging, i want the variable (name) to be a variable, but
if not, I want it to be a constant. When I compile this, the preprocessor
starts complaining at the fourth line, because of the second #define. Is
this OT here? And if not, how should I solve this?

the d0ct0r
 
G

gnuyuva

Hey,

please consider the following:

#if DEBUG
#define SOMEMACRO(type, name, value) (type) (name) = (value)
#else
#define SOMEMACRO(type, name, value) #define (name) (value)

Why don't you define this macro like this:
#define SOMEMACRO(type, name, value) static const type name = value;

With such constructs, you can construct complex types also, not only
PODs.
 
J

James Kanze

please consider the following:
#if DEBUG
#define SOMEMACRO(type, name, value) (type) (name) = (value)
#else
#define SOMEMACRO(type, name, value) #define (name) (value)
#endif
If I define DEBUGging, i want the variable (name) to be a
variable, but if not, I want it to be a constant. When I
compile this, the preprocessor starts complaining at the
fourth line, because of the second #define.

The results of macro expansion are not processed as
pre-processing declarations, even if they look like one.
Is this OT here?
No.

And if not, how should I solve this?

You can't use a macro to generate a #define. On the other hand,
you don't want to use #define for constants in C++ anyway.
Something like:

#if DEBUG
#define SOMEMACRO( type, name, value ) type name = value
#else
#define SOMEMACRO( type, name, value ) type const name value
#endif

would probably work. (Note that you cannot put parentheses
around the type. A declaration like:
(int) (toto) = (10) ;
is not legal. You might also want to make the variables
static.)

Also, I very seriously question the wisdom of this. If there's
any reason for the values to not be const, don't make them
const. And if there's not, they should be const in the debug
build as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,177
Latest member
OrderGlucea
Top