Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    
}

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading