Question

I have an array of 255 elements. I need to store 100 values in this array. For example, if there are 3 items rose, red, rat then arr[0] should represent rose, arr[1] should represent red and arr[2] as rat. Then these values are assigned as arr[0] = 100, arr[1] = 200, arr[2] = 300. Now when I want to get the value of rat I should be able to get the value directly by accessing its index i.e arr[2]=300. My idea is to create macros and assign values to each items and directly access the value in array. Example:

#define ROSE 0 
#define RED 1
#define RAT 2

Then directly for rat I will say arr[RAT] to get the value. Is this a good approach for 100 items? ADDITION: Now what if the size of values of items vary? For ex. red has the 4bytes value and rat has 2bytes value, then for uint8 arr[255]; red should starts at arr[1] and rat should start at arr[5]. Does enum still work here?

Was it helpful?

Solution

You can also use C Enumeration Declarations, enums:

typedef enum {rose, red, rat} index; 

Now in your code you can access arr[rat] that is == arr[2].

Generally I avoid macro for this kind of constants (where many constants are of similar types). I think it should be a type with a user defined domain that is enum.

An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name of the (optional) enumeration tag and defines the set of named integer identifiers (called the "enumeration set," "enumerator constants," "enumerators," or "members").

Macro I will prefer for array size:

#define SIZE  100;

int arr[SIZE]

Thanks to @junix to add very nice point in my answer:

It will be nice idea to defined enum with to add a last element that give total number of elements, e.g.:

typedef enum { rose, 
               red, 
               rat, 
               /* add new elements here */ 
              item_count
        } index;

Now my enum domain range is [0, item_count], and we can use item_count value for example like:

int arr[item_count];

And of-course this benefit we don't have with macros!

OTHER TIPS

It might be a better approach to use enumeration instead:

enum Item {
    ROSE = 0,
    RED = 1,
    RAT = 2
};
arr[RAT]=300

enum structures are easier to extend (add a new item, insert a new item and increment the indexes of the others). If you use macros you'll have to do this manually.

You should use an enum:

enum {ROSE, RED, RAT, ...}

It better express your intent. You are sure that different tag will get different value. Also if later you use a switch, you'll get warning if you forgot some index.

Actually, this sounds like an ideal candidate for a hash table.

Having to maintain 100 seperate symbols is going to be pain, whether they are macro definitions or enums.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top