1

I'm working on building a watch based on the Arduino/ATMega. The primary goal for now is to switch between "modes” (different functions) by pressing a button on the side. Initially, I had a long if statement like this:

if (counter == 0) 
    mode1();
    enter code 
else if (counter == 1)
    mode2();
    .... Repeat....

But that seems inefficient. So, I tried to make an array of the functions without actually calling them, and then call the indexed function later. The code segment is as follows (Apologies for the mess, it’s very much a WIP)


int Modes[3] = {showTime,flashlight,antiAnxiety} //these are all void functions that are defined earlier. 

int scroller(){
  int counter = 0;
    int timeLeft = millis()+5000;
    while (timer <= millis()){
       ...more code...
    }
  Modes[counter]();
}

However, when I try to compile that, I get an error:

Error: expression cannot be used as a function.

That logic works in Python, so I’m assuming there’s a concept I don’t know that gets abstracted away in higher-level languages. I’m quite willing to learn it, I just need to know what it is.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Ainsel
  • 13
  • 3

1 Answers1

1

The type is wrong - instead of int you need void (*)() as type (because you have an array of void someFunction() function pointers, not an array of integers - and while the former can be converted to the latter in a way, as memory address, you cannot call an integer).

void (*Modes[3])() = {showTime, flashlight, antiAnxiety};

This code becomes easier to understand with a type definition:

typedef void (*func_type)();
func_type Modes[3] = {showTime, flashlight, antiAnxiety};
CherryDT
  • 25,571
  • 5
  • 49
  • 74
  • Ok, I can work with that. Thanks! So invoking a function like that, without the parentheses, is referencing a pointer to the function? – Ainsel Aug 17 '20 at 19:13
  • "like that, without the parentheses" is not _invoking_ then (invoking = calling), I guess you mean referencing. Technically `myFunction` is of a function type, but [a function can be implictly converted to a _pointer_ to itself](https://stackoverflow.com/questions/16917043/do-function-pointers-need-an-ampersand): "An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function." - You could also write `&myFunction` but the result is the same because of the implicit conversion. – CherryDT Aug 17 '20 at 19:26