Search code examples
c++arrayscomparisonuint32-t

How to initialize and then later assign values to a uint32_t array in C++


I'm using C++ in Arduino to create a patternArray of random uint32_t values (colors), and compare those colors against colors a user enters via button from a predefined colorArray. The problem is that I need to initialize a random seed before I assign the random values, but I don't know the proper syntax (when I seem to get the syntax right, my color comparison evaluation fails).

uint32_t colorRed = pixels.Color(255, 0, 0);
uint32_t colorGreen = pixels.Color(0, 150, 0);
uint32_t colorBlue = pixels.Color(0, 255, 255);
uint32_t colorYellow = pixels.Color(255, 255, 0);

uint32_t colorArray[4] = {colorRed, colorGreen, colorBlue, colorYellow};
uint32_t patternArray;

void setup() {

  randomSeed(millis());
  patternArray[4] = {colorArray[random(4)], colorArray[random(4)], colorArray[random(4)], colorArray[random(4)]};
}

void loop(){
  if (colorArray[0] == patternArray[0]) { ... }
}

This throws the error:

invalid types 'uint32_t {aka long unsigned int}[int]' for array subscript

How do I do this properly so the comparison doesn't fail


Solution

  • In C++, you cannot assign to an array; you just can initialize it, i.e. in the course of its definition. So initializing an array as follows is OK,

    uint32_t colorArray[4] = {colorRed, colorGreen, colorBlue, colorYellow};
    

    while assigning to an array is not:

    uint32_t patternArray;
    patternArray = { 1,2,3,4 };
    

    In your code, you could assign to array members instead:

    void setup() {
    
      randomSeed(millis());
      patternArray[0] = colorArray[random(4)];
      patternArray[1] = colorArray[random(4)];
      patternArray[2] = colorArray[random(4)];
      patternArray[3] = colorArray[random(4)];
    }