Saturday, September 1, 2018

Declaring variables in macros in C, allowing a trailing semicolon

This is a silly problem with macro declarations, but one I've run into a few times and was curious if there is some solution I'm missing.



I have a macro that declares variables, which I want to ensure are not initialized by mistake.



#define DECLARE_FOO(var) \
int _##var##_a = 0; \
int _##var##_b = 0


Example use:




DECLARE_FOO(var);


however this allows...



DECLARE_FOO(var) + 1;


I could just ignore this (for now Im just leaving it this way), but I'd like to disallow it. simple...




#define DECLARE_FOO(var) \
int _##var##_a = 0; \
int _##var##_b = 0;


However now I have to remove the semicolon from the declaration otherwise I get this warning.



DECLARE_FOO(var);
int bar;



ISO C90 forbids mixed declarations and code [-Werror=declaration-after-statement]



So, I have to do this...



DECLARE_FOO(var)
int bar;



...which expands correctly, but looks odd for anyone reading the code and not checking the macro definition. Also editors that don't expand macros may warn about this as incorrect syntax.



Is there some way to disallow assignments to the variable but also end usage of the declaration with a semicolon ?



Update



It wasn't really clear in my question, but -Werror=declaration-after-statement infers that C90 is a requirement here, answers mixing in statements wont work in this case since there may be proceeding declarations.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...