Tuesday, April 9, 2013

Generic Functions In C Lanuguage

Most of the people use macros in C language to define constants only. But the powerful feature of macro is, its ability to generate generic functions. Till now most of the people have seen generic functions in object oriented programming only. In C we can create generic functions using macro. A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.
         
 Lets see the following example, where i am creating a generic function to find minimum number, out of 2 numbers using a macro.

// File Name: genericFunction.c

#include<stdio.h>
#define MIN(FunName, Dtype) \
        Dtype FunName(Dtype x, Dtype y)\
             { return x>y?y:x; }\

MIN(int_min, int)
MIN(float_min, float)

void main()
{
  int k;
  float l;
  k = int_min(5, 6);
  l = float_min(7.0, 6.9);
  printf("\n Min Integer is: %d", k);
  printf("\n Min float is: %f", l);
}

To Run: gcc  genericFunction.c
              ./a.out

In the above program i am using same macro to generate definitions for int_min, float_min functions, that means i have created a generic function for the same.

MIN(int_min, int) can be expanded as int int_min(int, int)  and
MIN(float_min, float) can be expanded as float float_min(float, float).

1 comment: