How to have contents of array change based on condition?

I'm trying to change the contents and length of an array based on a condition, and getting some unexpected behavior.

Stripped down code:

void setup() {
  Serial.begin(115200);  // Allows serial monitor output (check baud rate)
}


void loop() {

  bool condition = false;

  // this works
  int options[4] = {1, 0, -1, -1};  

  // things get weird if I dynamically build the array
  int options2[4];
  if (condition) int options2[3] = {1, 0, -1};
  else int options2[4] = {1, 0, -1, -1};   

  Serial.println(options[0]);
  // prints "1"
  
  Serial.println(options2[0]);
  // prints "20000"

  delay(100);
}

In the above, options[0] = 1, which is as expected. However options2[0] = 20000...

I'm guessing the reason is that I'm redeclaring options2, but I don't see how I change it's contents and length without doing so.

Any tips on how I can change the contents of options[], including the number of items, based on a condition?

For a hint about why that can't be expected to work, try this:

void setup() {
  Serial.begin(115200);  // Allows serial monitor output (check baud rate)
}

void loop() {
  bool condition = false;

  // things get weird if I dynamically build the array
  if (condition) int options2[3] = {1, 0, -1};
  else int options2[4] = {1, 0, -1, -1};   
  
  Serial.println(options2[0]);

  delay(100);
}

you can't change the length of an array at runtime.

declare the array with the biggest size that can occur
and then limit access to the array by any kind of mechanism

by changing a value of MaxIndex or insert a "-1"-value behind the last valid value of the array

If you describe the overall purpose that you want to achieve a good solution can be suggested.

best regards Stefan

The behaviour you are seeing is to do with variable scope.

If you declare a variable within an if statement then it only exists within that statement.

Try this...

void setup() 
{
  Serial.begin(115200);  

  if (true)
  { 
    int x = 5;
  }

  Serial.println(x);
  
}

void loop() 
{}
Program:10:18: error: 'x' was not declared in this scope
   Serial.println(x);

you could create dynamic arrays as required, e.g. using C library function - malloc() or how-to-create-a-dynamic-array-of-integers-in-cplusplus-using-the-new-keyword
however, avoid dynamic structures (e.g. malloc(), String class, etc) on small microcontroller such as the UNO - memory can become fragmented and run out of memory when attempting to allocate new storage

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