Home > front end >  Do I have to initialize function pointers one by one?
Do I have to initialize function pointers one by one?

Time:01-06

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

#include<stdio.h>

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[0]=add;
    ptr[1]=subtract;
    ptr[2]=multiply;
    
    ptr[2](3,5); //15
    
}

CodePudding user response:

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.

CodePudding user response:

You need to initialize during declaration.

//array of function pointers

#include<stdio.h>

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) = {add, subtract, multiply};
    
    ptr[2](4,5); //20
    
}
  • Related