1

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?

4
  • 4
    list is an int, not an array. You can't index it like that. Commented Jun 26, 2021 at 15:07
  • 2
    Did you mean int index(int val,int* list)? Commented Jun 26, 2021 at 15:07
  • You're list parameter is just a simple int. You'd want to update this to be an int* or maybe even an std::vector reference. You'd then just need to update the calling code to work with this. Commented Jun 26, 2021 at 15:08
  • @WillMoffat Your Commented Jun 26, 2021 at 16:37

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.