0

Say I have a list of defines MC_SERVER1, MC_SERVER2, MC_SERVER3 how would I loop thru to get the contents of each. Also I do not know how many I will have. I might have 3 or 10. This is for C programming

Say I have DEFINE MC_SERVER1="mc1.sdsds.com" DEFINE MC_SERVER2="mc2.sdsds.com"

how do I loop thru them all.

Craig Sparks
  • 23
  • 1
  • 2
  • 6
  • 3
    Short answer: You don't. What problem are you trying to solve? – Mysticial Mar 30 '12 at 04:19
  • Define "content". What are your macros? Constants? Expressions? Please explain in more detail what you intend to accomplish. – vsz Mar 30 '12 at 04:22
  • 1
    I guess he means something like `for (i=0;i – iehrlich Mar 30 '12 at 04:27
  • I don't think that it be possible. (C is not a very dynamic language, and the C preprocessor doesn't have reflection features.) –  Mar 30 '12 at 04:30
  • The syntax is not `DEFINE MC_SERVER1="mc1.sdsds.com"` it's `#define MC_SERVER1 "mc1.sdsds.com"` – vsz Mar 30 '12 at 04:33

3 Answers3

3

Defines don't work that way. They are evaluated at compile time, not execution time, so instances of them are replaced with their values.

SuperRod
  • 557
  • 3
  • 8
  • `#define GETCONFIGVALUE(key, sect, var) \ config_get_value(key, sect, var); \ if (strlen(var) > 0) \ TRACE(TRACE_DEBUG, "key "#key" section "#sect" var "#var" value [%s]", var) ` – Craig Sparks Mar 30 '12 at 04:31
  • This is what I am looking at in the source so it leads me to believe that these are the values from the config file – Craig Sparks Mar 30 '12 at 04:32
  • @Craig Sparks: `#key` is called stringification (http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification). You should avoid it unless you are very sure you know what you are doing. – vsz Mar 30 '12 at 04:34
  • 1
    That's a nasty macro, won't behave well as an if-then block. This is why lots of macros are wrapped with do {} while (0) as this should be. – blueshift Mar 30 '12 at 05:13
0

There is a possibility to obtain similar effects with macros, through tricks with concatenation (##) and stringification (#), but it would probably be better for you to just don't use macros.

See Variable names in C for examples.

Community
  • 1
  • 1
vsz
  • 4,811
  • 7
  • 41
  • 78
0

You can do this if they are in an array, but not just with a list of defines as you have.

Such as:

const char *servers[] = {
  "server.one",
  "server.two",
};

If you're interested in this approach, also see how to get the length of an array at compile time

Community
  • 1
  • 1
blueshift
  • 6,742
  • 2
  • 39
  • 63