tags:

views:

113

answers:

4

I know that this will not work, but hopefully you can see what I'm trying to do

#if ASSIGN_ALLOWED
    #define MAYBE_SKIP_REST_OF_LINE 
#else
    #define MAYBE_SKIP_REST_OF_LINE ; //
#endif

char str[80]  MAYBE_SKIP_REST_OF_LINE = "Hello\n";
long array[3] MAYBE_SKIP_REST_OF_LINE = { 7,8,9 };
int x         MAYBE_SKIP_REST_OF_LINE = 3;
//...many many more similar lines...

Is there a way to do this such that it works?

A: 

As comments are filtered out in the preprocessor run, i dont think so

psychoschlumpf
+8  A: 

Sure:

#ifdef ASSIGN_ALLOWED
    #define OPTIONAL_INITIALISER(x) = x 
#else
    #define OPTIONAL_INITIALISER(x) 
#endif

char str[80] OPTIONAL_INTIALISER("Hello\n");
#define ARRAY_INIT { 7,8,9 }
long array[3] OPTIONAL_INITIALISER(ARRAY_INIT);
#undef ARRAY_INIT
int x OPTIONAL_INITIALISER(3);

Any initialisers containing commas, like for array in the example, will need to be expanded from their own macro, like ARRAY_INIT in the above. If your compiler supports C99 varargs macros, then you can instead do it in a cleaner way:

#ifdef ASSIGN_ALLOWED
    #define OPTIONAL_INITIALISER(...) = __VA_ARGS__ 
#else
    #define OPTIONAL_INITIALISER(...) 
#endif

char str[80] OPTIONAL_INTIALISER("Hello\n");
long array[3] OPTIONAL_INITIALISER({ 7,8,9 });
int x OPTIONAL_INITIALISER(3);
caf
won't the commas in the 7,8,9 cause the preprocessor to think the macro has been given three arguments?
Mick
Mick: Ahh yes, altered to fix this.
caf
Hmmmm, not so pretty now :-(
Mick
__VA_ARGS__ now, that's better.
Mick
another suggestion: add the braces to the macro definition, ie `= { __VA_ARGS__ }` ; this works for scalar types as well: `int foo = { 4 };` is valid C
Christoph
A: 

It would depend on how the preprocessor worked with comments and macros. If it strips comments after macro expansion then your smooth sailing, but otherwise it might not work simply due to the preprocessor implementation.

You could try this? (it would be messy though).

#define MAYBE_SKIP(code) code
#define MAYBE_SKIP(code) /* code */
Nick Bedford
Comments are stripped before too early for that to work. Maybe you should check before suggesting answers; it will avoid down-votes. (No, it wasn't mine.)
Jonathan Leffler
A: 

The preprocessor strips out commented sections. Try running

gcc -E source.c

This will run the preprocessor on your code but will not actually compile it, allowing you to see what happens after macro expansion. You should notice that all the comments are gone from any expanded macros.

Artelius
Accurate observation - but no suggestion for how to achieve the desired result.
Jonathan Leffler