2

Suppose that, I have following macros that are defined in header file:

# define MACRO_ID_1        1
# define MACRO_ID_2        2
...
# define MACRO_ID_1000     1000

In main.c, I will input a string like MACRO1, MACRO2... I would like to write a function to output macro from input string

int func_string2macro (char* string)
{ 
  ...
  return <macro_similar_to_string>;
}

For using : func_string2macro("MACRO1") then it will return MACRO_ID_1

I found that switch/case can be solved this issue But with a alot of macro (1000) then switch/case method is not good.

Anyone can support me?

bvp147
  • 83
  • 1
  • 8

1 Answers1

1

I guess you can try the following:

Step 1 - Extract the number part out of string (e.g for MACRO_ID_48 it will be 48)

Step 2 - Return the number

Of course that this solution is only relevant for the naive approach in which the number in 'define' value name represents the value.

Another option for you (in case the number in the 'define' name is not equal to the value -

Step 1 - Create an array with the same size as the values of your 'define'

Step 2 - In init, set each value in the array to match 'define' initial value

Step 3 - Once you've parsed the number from 'string' - return value saved in the array

Community
  • 1
  • 1
dear_tzvi
  • 745
  • 6
  • 19
  • my case the number value in define is not matched with string. Using array for a lot of data (many define value) is not good. any suggestion? – bvp147 Feb 18 '16 at 09:22