Can a array and variable access the same data? (defines/declaration/struct question))

I define my cell voltages intuitively as these variables:
uint16_t C1 = 3720;
uint16_t C2 = 3735;
uint16_t C3 = 3750;
uint16_t C4 = 3855;
uint16_t C5 = 3855;

...but then I cannot "just" do an array operation on them.
If I store them as array:
uint16_t array[cells]{3720, 3680, 3770, 3750, 3500, 3500};
then I cannot access them as the intuitive C1 (is cell) - because now cell one is cells[0]

Question:
can I have the best of both worlds? having an array, and be able to have a "variable name" for each of the items?

Sure, try this:

int C1 = 0;
uint16_t array[cells] = {3720, 3680, 3770, 3750, 3500, 3500};
Serial.println(array[C1]);
1 Like

Maybe consider something like this

enum
{
    C1,
    C2
};

int array[2];

void setup()
{
    Serial.begin(115200);
    array[C1] = 3720;
    array[C2] = 3735;

    Serial.println(array[C1]);
    array[C1] = 999;

    Serial.println(array[C1]);
}

void loop()
{
}

2 Likes
uint16_t array[cells] = {3720, 3735, 3750, 3855, 3855};

#define C1 array[0]
#define C2 array[1]
#define C3 array[2]
#define C4 array[3]
#define C5 array[4]
1 Like

thank you, for my application, this is clearly the cleanest way to do it.

It's not intuitive or counter-intuitive, it's just habit, convention.

Think of the "first" index in an array as the "base" index, which is zero, not one. Once you get used to it, you will realise it makes just as much sense. Referring to the base index of an array as index zero or index one is arbitrary.

2 Likes

ES.31: Don’t use macros for constants or “functions”

If you do need an alias for the array elements, use a reference instead:

auto &C1 = array[0];
auto &C2 = array[1];
// ...
2 Likes

another solution is to have the first array-element as a "dummy"

//                      unused dummy  C1    C2    C3    C4    C5
uint16_t myCellNo[6] = {0,            3720, 3735, 3750, 3855, 3855};

and to simply not use myCellNo[0]

best regards Stefan

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.