Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a static array of pointers to functions in C++?

Tags:

c++

c

pointers

I need a global array of function pointers, and came up with this:

static int (*myArray[5])();

if i am right, this is "a global array of pointers to functions returning int". Is that right? Or is it "an array of pointers to functions returning a static int". I just need a quick answer.

like image 811
Susan Yanders Avatar asked Dec 09 '22 13:12

Susan Yanders


2 Answers

Should be made as simple as possible, but not simpler:

typedef int (*t_MyFunc)();

t_MyFunc g_MyFuncArray[5];

And g_MyFuncArray can be static if you wish (but you should not if you want a global variable):

static t_MyFunc g_MyFuncArray[5];

In a header file you should write:

extern t_MyFunc g_MyFuncArray[5];

But don't forget to omit the static keyword in a .cpp file in this case.

like image 161
Sergey K. Avatar answered Feb 11 '23 04:02

Sergey K.


You don't want or need the static keyword for a global variable. In a .cpp file using static will give the variable internal linkage (you want external linkage). Without the static, myArray is functionally global only to the file. If you want it visible to your entire program you add extern int (*myArray[MY_FUNC_ARRAY_SIZE])(); to your .h file.

like image 45
Tod Avatar answered Feb 11 '23 05:02

Tod