-2
void func(int a){
    byte arr[a];
}

this code is not working. how I assign array length by using parameter?

song
  • 1
  • 1
  • Declaring a variable of any kind inside a function is asking for troubles in CAPL from my experience. If you'd like a more positive feedback, [edit](https://stackoverflow.com/posts/65488787/edit) your question to explain _why_ it is not working. Does it return error? Does it work in a way you don't mean for it to work? – Daemon Painter Jan 15 '21 at 08:51

1 Answers1

0

In CAPL you have many options to go, but first you'll have to consider you probably want to step back and ask yourself if you really need variable array size at runtime. The measurement performance is what you should be concerned about, declaring a suitable array size as design may be a safer approach.

A global array of parametric size could be something like this:

variables
{
    int arraySize = 256;
    byte arr[arraySize];
}

From the docs,

Declaration of arrays (arrays, vectors, matrices) is permitted in CAPL. They are used and initialized in a manner analogous to C language.

In C, array size is constant:

Array is a type consisting of a contiguously allocated nonempty sequence of objects with a particular element type. The number of those objects (the array size) never changes during the array lifetime. [source]

This is why your code is not working: you cannot create an array of runtime-based size. Similarly, from the same source

Variable-length arrays

If expression is not an integer constant expression, the declarator is for an array of variable size.

Each time the flow of control passes over the declaration, expression is evaluated (and it must always evaluate to a value greater than zero), and the array is allocated (correspondingly, lifetime of a VLA ends when the declaration goes out of scope). The size of each VLA instance does not change during its lifetime, but on another pass over the same code, it may be allocated with a different size.

This is why you should be able to define a parametric array like I showed you. Even if in the code arraySize should change, arr will be of 256 elements for the execution of your CAPL script.

void func(int a){
    byte arr[a];
}

Will throw error, because int a is determined to be of non-constant time, thus violating the requirements above. What you can do, is to memcpy parts of a larger array to a location of choice, for example a smaller array, or employ a number of "buffer" arrays as you often see in CAPL scripts.

As I took it home, the gist of it is: use a larger size array, and be precise about where you are putting your information inside of it. Note that you must be precise, because every element in the array contains some kind of data, at init most of it is non-sense, and there is no safeguard for you against this digital noise.

Daemon Painter
  • 3,208
  • 3
  • 29
  • 44