问题
This is a follow-up question after this (please read my question to the end) :
how to avoid name conflicts coming from #define in C? (or C++)
Suppose I define ROW and COL using #define. I then define ARRSIZE using ROW and COL. I declare a static array like float myarray[ARRSIZE];. When I modify ROW and COL, the static array size changes accordingly. But in my special case, the names ROW and COL name-conflicts with a member name of a struct type I'm using in the same file. Someone told me to use const variable instead of using '#define' to avoid the confict. I liked that I modifed the code as beloow(it's an exmple).
const int ROW = 100;
const int COL = 200;
const int ARRSIZE = ROW*COL;
float myarray[ARRSIZE];
Compling this gives me
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'ARRSIZE'
at the line where I define ARRSIZE. Of course I can use int ARRSIZE = ROW*COL; inside a function and dynamically allocate the array inside the function using malloc. But what if I want to change only ROW and COL and don't want to use malloc? Of course there is no problem (except the name conflicts) when doing it with #define.
#define ROW 100
#define COL 200
#define ARRSIZE ROW*COL
float myarray[ARRSIZE];
So the problem : I want to change only ROW, COL and want the static array size automatically changed, but at the same time, ROW and COL appears as a member variable of a type(a struct) in the same source file, and I cannot fix member name of the type(suppose it's from a header file provided by the system). So in a word, I want to define a 'macro like values' that is not applied to a member function/variable or global variables. What is the best practice to do it in my case? just change my variable ROW and COL to something special? Having asked this question, I get an impression that may be the only solution.. :)
回答1:
Compiling comments to make an answer:
Solution A,
if you for some reason have to stick with "ROW" and "COL" in your code (credits to melpomene):
enum { ROW = 100 };
enum { COL = 200 };
enum { ARRSIZE = ROW*COL };
Solution B,
if you are free to choose identifiers; more robust for future reuse:
Avoid the naming conflict by choosing different, non-conflicting, longer identfiers.
I have a superstitious distrust of short, obvious identifiers, the conflict you encountered is a good example why. Other examples have cost my employers quite some time and money.
(I have seen melpomene elsewhere not being interested in the reputation for an answer anymore, very altruistical. I think it is worth making a nice Q/A pair here and does not take anything from melpomene.)
来源:https://stackoverflow.com/questions/43884007/in-c-how-to-define-a-macro-using-other-macros-when-that-other-macros-raise-nam