How to keep matching between row and index in C?

I have an enumeration for example.

enum {
APPLE,
MANGO,
BANANA
}

and the corresponding array of strings

char fruits[] = 
{
 "apple",
 "mango",
 "banana"
}

I need to get the row index if I have a row. Therefore, given that the string is an apple, I need to get 0 and so on. [ Enummay also help the solution]

Is there an elegant way to keep [apple,0],[banana,1]that short and simple that I can use as a macro. I don't need long things like a hash table. Can it Enumhelp in displaying?

+4
source share
4 answers

You can do something like

entries.h

 ENTRY(APPLE, "apple"), 
 ENTRY(MANGO, "mango"),

In your file

#define ENTRY(a,b) b
const char *fruits [] = {
#include "entries.h"
} ; 

#undef ENTRY
#define ENTRY(a,b) a
enum fruit_t
{
#include "entries.h"
} ;
+10
source

"" C.

:

typedef enum {
  INVALID = -1,

  APPLE = 0,
  MANGO,
  BANANA,

  NUM_FRUIT,
} fruit_t;

// NOTE: These indices must be kept in-sync with fruit_t!
const char* fruits[] = {
 "apple",
 "mango",
 "banana"
};

fruit_t lookup_fruit(const char* name) {
    int i;
    for (i=0; i<NUM_FRUIT; i++) {
        if (strcmp(name, fruits[i]) == 0)
            return i;
    }
    return INVALID;
}

void test(void) {
    fruit_t result = lookup_fruit("mango");
}
+4

In C99 or C11, you can use designated initializers:

enum { APPLE, MANGO, BANANA = 7 };

char *fruits[] = 
{
    [BANANA] = "banana",
    [MANGO]  = "mango",
    [APPLE]  = "apple",
};

This works correctly even if the items are not listed in the same order, and even despite the large gap between MANGO and BANANA.

+2
source

This is an alternative layout for user3344003, which does not require every .c file to provide furniture; and includes guards:

// entries.h
#ifndef H_ENTRIES
    // other stuff for this header file that needs to be in header guards
#endif

// make sure to only include the enum once even if the file is multiply included
#if (!defined H_ENTRIES) || (defined C_ENTRIES)

#ifndef C_ENTRIES
    enum 
    {
#   define ENTRY(a,b) a
#endif

    ENTRY(APPLE, "apple"), 
    ENTRY(MANGO, "mango"),

#ifndef C_ENTRIES
    NUM_FRUITS
    };
    extern const char *fruits[NUM_FRUITS];   // if you also want array extern of course
#   undef ENTRY
#   define H_ENTRIES
#endif

// entries.c

#define C_ENTRIES
#define ENTRY(a,b) b

    const char *fruits[NUM_FRUITS] = {
#       include "entries.h"
    };

// other.c 

#include "entries.h"
0
source

Source: https://habr.com/ru/post/1541989/


All Articles