Array index names

Does anyone know if it's possible to name indexes for arrays? For example:

int myArray[2];

myArray['Bob'] = 1;
myArray['Fred'] = 2;

Instead of traditionally using numbers for the array indexes? This is possible in other languages but I can't see to get it with the Arduino or find references to it.

Bob and Fred are multi character constants, so whilst legal, their values are quite high, and probably off the end of RAM.
What is it you are trying to do?

How about

#define BOB 0
#define FRED 1

int myArray[2];

myArray[BOB] = 1;
myArray[FRED] = 2;

monkey123:
Does anyone know if it's possible to name indexes for arrays? For example:

int myArray[2];

myArray['Bob'] = 1;
myArray['Fred'] = 2;




Instead of traditionally using numbers for the array indexes? This is possible in other languages but I can't see to get it with the Arduino or find references to it.

No, it's not. Probably you want to use constants or #defined(d) symbols:

const int BOB = 1;

myArray[BOB];

Or:

#define BOB 1

myArray[BOB];

An enum also seems to fit the bill for what you are trying to do.

enum Color {Red, Green, Blue};

int ledPins[] = {9, 10, 11};

void setup()
{
analogWrite(ledPins[Red], 45);
analogWrite(ledPins[Green], 155);
analogWrite(ledPins[Blue], 0);
}

void loop()
{
}

Damn, why do I always forget about enums ? Thanks for reminding me of them! :slight_smile:

why do I always forget about enums ?

I think that they are often overlooked, and complex solutions invented to accomplish the same functionality.

Don't forget the enum is not limited to integer values, nor linear progressions, nor does it need to start at 0, though those are all default properties.

enum Color {Red=-6, Green=9, Blue=4};

is a valid enum declaration (although useless in this instance).

enum Color {Red=9, Green=10, Blue=6};
analogWrite(Red, 45);
analogWrite(Green, 155);
analogWrite(Blue, 0);

would also work, and allow a non-linear progression of pins with no array needed (though I think the original example is clearer).

Thanks for reminding me that :slight_smile:

enums can make your code more readable and in some cases, errors a bit harder to make.

IIUC the Arduino makes a memory copy of every constant, literal, etc, in your code and I don't know if it compiles to the smallest size or the size of a variable it involves with or what. To play it safe, I declare variables in the size I want. It's not like I have RAM to waste.