1

Let's say I want to create 10 functions, named Function1, Function2 until 10. Each function is used if a certain variable is equal to its number. Rather than using individual functions, I was wondering if its possible to use some sort of array concept for functions when it comes to naming? I tried reading about it and saw pointers but I honestly didn't understand what I saw about it because I'm not that adept to the language yet.

1
  • Of course this is possible, you can make an array of any data type you like. And a function pointer is a data type. But this is a broad issue, so you rather get a good book or online resource on C++ and start to learn. Mar 2 at 8:10
4

Here's an example of how to do it:

jump_table.ino

int func1(int arg)  { return arg + 1; }
int func2(int arg)  { return arg + 2; }
int func3(int arg)  { return arg + 3; }
int func4(int arg)  { return arg + 4; }
int func5(int arg)  { return arg + 5; }
int func6(int arg)  { return arg + 6; }
int func7(int arg)  { return arg + 7; }
int func8(int arg)  { return arg + 8; }
int func9(int arg)  { return arg + 9; }
int func10(int arg) { return arg + 10; }

int (*jump_table[10])(int) = { func1, func2, func3, func4, func5, 
                               func6, func7, func8, func9, func10 };
    
void setup() {
}
    
void loop() {
  int index = 2;
  int argument = 42;
  int result = (*jump_table[index])(argument);
  // result is 45
}

All functions stored in the array must have the same signature. This simply means that they must return the same type (e.g. int) and have the same arguments (a single int in the example above).


You can do the same with static class methods (but not instance methods). For example you could use MyClass::myStaticMethod in the array above but not MyClass::myInstanceMethod nor instance.myInstanceMethod:

class MyClass {
public:
  static int myStaticMethod(int foo)   { return foo + 17; }
  int        myInstanceMethod(int bar) { return bar + 17; }
}

MyClass instance;

There's a similar question over on stackoverflow.

3
  • Hi, is argument different from arg? But it seems like your code is correct.
    – AndroidV11
    Mar 2 at 21:44
  • @AndroidV11 The value of argument gets passed to the appropriate function where it available as arg (or foo in the class example). BTW, based on your comment it sounds like you're pretty new to programming. If that's the case I'd recommend learning more of the basics of C++ before you use this technique; it's fairly advanced and really only makes sense to use in specialized situations (e.g. remote procedure call handlers). Mar 2 at 22:30
  • @AndroidV11 I just fixed a rather nasty typo in the code. C++ uses zero-based array indices so to call the third function index needs to be 2, not 3. Mar 2 at 23:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.