Function Pointers with Structures in C

 Function Pointers with Structures in C


Function pointers can be combined with structures to create powerful and flexible data structures that encapsulate both data and behavior.



#include <stdio.h>


struct Operation {

    int (*perform)(int, int);

};


int add(int a, int b) {

    return a + b;

}


int subtract(int a, int b) {

    return a - b;

}


int main() {

    struct Operation op1 = {add};

    struct Operation op2 = {subtract};


    int result1 = op1.perform(5, 3);

    int result2 = op2.perform(5, 3);


    printf("Result 1: %d\n", result1);

    printf("Result 2: %d\n", result2);


    return 0;

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...