Reputation: 404
I have recently started working with the Arduino (which is C++).
When I run the below function (along with other code):
int index(int val,int list) {
int i;
for (i = 0; i < 8; i++) {
if (val == list[i]) {
return i;
}
return null;
}
}
I get an error on the line if (val == list[i]) {
:
invalid types 'int[int]' for array subscript
I have two questions: Why is the error happening, and is there some better way to get the index of a value in an array without using complex syntaxes?
Upvotes: 1
Views: 2344
Reputation: 308
Same answer as the accepted one, but with more recent c++ features :
int index(int val, int *list)
{
auto it = std::find(list, list + 8, val);
if( it == list + 8 )
{
return -1; // if no match found
}
else
{
return distance(list, it);
}
}
Note: you need to return an integer value instead of null, since the return type of the function is int.
Upvotes: 0
Reputation: 1529
you should accept as an array
instead of single-variable in function:
int index(int val, int *list) {
int i;
for (i = 0; i < 8; i++) {
if (val == list[i]) {
return i;
}
}
/* if no match found */
return -1;
}
Note: you need to return an integer value instead of null
, since the return type of the function is int
.
Upvotes: 3