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.

0

1 Answer 1

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};
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I can work with that. Thanks! So invoking a function like that, without the parentheses, is referencing a pointer to the function?
"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: "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.

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.