Creating an Array of Function Pointers in C for Integer-to-Float Operations

29 Dec 2022 Balmiki Kumar 0 C Programming

Defining a Function Pointer Array for Integer-to-Float Transformations in C

Declaring an array of three function pointers where each function receives two integers and returns float in C means creating an array that holds pointers to three functions. Each function should accept two integers as input parameters and return a floating-point value.

In C, functions are first-class citizens, which means they can be passed as arguments to other functions, returned as values from functions, and stored in arrays. Function pointers are variables that hold the memory addresses of functions. They can be used to call functions indirectly.

To declare an array of function pointers, you need to define the function signature (i.e., the return type and parameter types) and create a typedef for the function pointer type. Then, you can declare an array of that function pointer type and initialize it with pointers to the actual functions.

Syntax

float (*fn[3])(int, int);

Creating an Array of Function Pointers in C for Integer-to-Float Operations

#include<stdio.h>
float (*fn[3])(int, int);
float add(int, int);
int main() {
 int x, y, z, j;
 for (j = 0; j < 3; j++){
 fn[j] = &add;
 }
 x = fn[0](10, 20);
 y = fn[1](100, 200);
 z = fn[2](1000, 2000);
 printf("sum1 is: %d \n", x);
 printf("sum2 is: %d \n", y);
 printf("sum3 is: %d \n", z);
 return 0;
}
float add(int x, int y) {
 float f = x + y;
 return f;
}
Output:
sum1 is: 30
sum2 is: 300
sum3 is: 3000

Attention please: Here 'fn[3]' is an array of function pointers. Each element of the array can store the address of the function 'float add(int, int)'. fn[0]=fn[1]=fn[2]=&add Wherever this address is encountered add(int, int) function is called.

 

Example 02:Array of Function Pointers in C for Integer-to-Float Conversions: A Practical Guide

typedef float (*ArithmeticFcn)(int, int);

float add(int a, int b) {
    return (float)(a + b);
}

float subtract(int a, int b) {
    return (float)(a - b);
}

float multiply(int a, int b) {
    return (float)(a * b);
}

int main() {
    ArithmeticFcn arithmeticFunctions[3] = {add, subtract, multiply};
    return 0;
}

In this example, we define the ArithmeticFcn type as a pointer to a function that takes two int parameters and returns a float. Then, we define three functions add, subtract, and multiply, each of which takes two int parameters and returns a float. Finally, we declare an array arithmeticFunctions of three ArithmeticFcn pointers and initialize it with pointers to the add, subtract, and multiply functions.

 

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.