Function Overloading in C

//Function overloading in C language
/*
Does C support function overloading?
This feature is present in the most of the object-oriented languages such as c++ and java
But C is not object-oriented language and doesn't support to function overloading.
But we can achieve this concept indirectly in C.

*/
#include<stdio.h>
#include<malloc.h>

struct struct1{
int data;
};
struct struct2{
float data;
int data1;
};

int foo(void* arg1, int arg2){

if(arg2==0){
struct struct1 *ptr=(struct struct1*)malloc(sizeof(struct struct1));
printf("in struct type struct1\n");
}else if(arg2==1){
struct struct2 *ptr2=(struct struct2*)malloc(sizeof(struct struct2));
printf("in struct type struct2\n");
}else{
//handler error if other structure is passed
printf("not identified\n");
}
return 0;
}
 int main(){

//suppose above second parameter arg2 contains different values of different structures
//such as 0=struct1 , 1=struct2 etc.
//Doesn't matter what the structure contains
struct struct1 *arg1=(struct struct1*)malloc(sizeof(struct struct1));
foo(arg1,0);//arg1 is pointer to struct type struct1 variable

struct struct2 *arg2=(struct struct2*)malloc(sizeof(struct struct2));
foo(arg2,1);//arg1 is pointer to struct type struct2 variable

//identifying the structs using the second parameter arg2
foo(10,2);

return 0;
}//main

Comments

Popular Posts