[SOLVED] How to access a macro from a string containing its name

Issue

In C, if I have

#define NUMBER_TWO 2
char* string = "NUMBER_TWO";

How can I get from string to the value 2?

Solution

Perhaps OP is interesting is some macro code abuse?

Use #macro_parameter to form the string "macro_argument".

#include <stdio.h>
#define NUMBER_TWO 2
#define NUMBER_THREE 3
#define NUMBER_FOUR 4
#define TEST_AND_RETURN(s, m) \
    do { if (strcmp((s), #m) == 0) return (m); } while (0)

int string_to_value(const char *s) {
  TEST_AND_RETURN(s, NUMBER_TWO);   // Only 1 coding of NUMBER_TWO
  TEST_AND_RETURN(s, NUMBER_THREE);
  // Maybe the clear way instead, or are 2 NUMBER_FOUR a concern?
  if (strcmp(s, "NUMBER_FOUR") == 0) return NUMBER_FOUR;
  return -1;
}

int main() {
  char* string = "NUMBER_TWO";
  printf("%d\n", string_to_value(string));
  printf("%d\n", string_to_value("NUMBER_THREE"));
  printf("%d\n", string_to_value("NUMBER_FOUR"));
}

Output

2
3
4

Answered By – chux – Reinstate Monica

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *