Arrays
You can use arrays in Spice for any primitive or custom struct data type.
Usage¶
To initialize an array e.g. of type string, you can write:
| Spice | |
|---|---|
The 3 in the brackets is the size of the array. The initial values can be provided in curly braces after the assign operator and
must be of the same data type.
You can only initialize an array with the number of items equal the arrays size or no items.
| Type | Default value |
|---|---|
int |
0 |
double |
0.0 |
string |
"" |
bool |
false |
struct |
Instance with default values for all fields |
To access an array item, you can use the index. The indexes are >= 0 per definition:
| Spice | |
|---|---|
More complex expressions for initial array values and item indexing are possible. Here's an example:
| Spice | |
|---|---|
Arrays as parameters¶
Like in C, an array parameter decays to a pointer to the callers array. No copy is made when calling the function, so assigning to an item of the parameter modifies the array of the caller:
| Spice | |
|---|---|
If you want the callee to work on its own copy, pass a copy explicitly. To hand over an array of arbitrary size, use an
unsized array parameter (e.g. int[]) instead, which is a plain pointer without a known item count.