Optional initializer using preprocessor trickery?
I know it won't work, but hopefully you can see what I am 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 make it work like this?
source to share
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 initializers containing commas, such as for array
in this example, must be expanded from a native macro, such ARRAY_INIT
as the one above. If your compiler supports C99 varargs macros, you can 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);
source to share
It will depend on how the preprocessor handled comments and macros. If it strips comments after macro expansion then your transition is smooth, but otherwise it may not work simply because of the preprocessor implementation.
Could you try this? (that would be messy though).
#define MAYBE_SKIP(code) code
#define MAYBE_SKIP(code) /* code */
source to share
The preprocessor highlights sections of comments. Try to run
gcc -E source.c
This will run the preprocessor in your code, but it won't actually compile it, allowing you to see what happens after the macro expansion. You should notice that all comments have disappeared from any extended macros.
source to share