Do I have to initialize function pointers one by one?

When I initialize function pointers in one take, like below, it does not work.

ptr[3]={add, subtract, multiply};

This gives:

[Error] expected expression before ‘{‘ token

However, one-by-one initialization works. Why is this?

//array of function pointers


void add(int a, int b){
    printf("%d\n", a+b);

void subtract(int a, int b){
    printf("%d\n", a-b);

void multiply(int a, int b){
    printf("%d\n", a*b);

int main(){
    void (*ptr[3])(int, int);
    //ptr[3]={add, subtract, multiply};  this initialization does not work
    //but this works
    ptr[2](3,5); //15

>Solution :

In the assignment, ptr[3]={add, subtract, multiply}; the RHS is (correctly) a suitable initializer-list for an array of three function pointers. However, the LHS (ptr[3]) is wrong: that’s just a single element of an array, and an out-of-bounds element, at that.

Just do the ‘assignment’ in the declaration, and make it an initialisation:

int main(void)
    void (*ptr[3])(int, int) = {add, subtract, multiply}; // this initialization does work
    ptr[2](3, 5); //15

There is actually nothing special, here, related to the fact that your array’s elements are function pointers. No array can be "assigned to" (using the = operator) en bloc, at any point other than in its declaration. In a variable declaration, the use of the = token isn’t, formally, an assignment operation; it is an initialisation. Useful reading: Initialization vs Assignment in C.

Leave a Reply