C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Function overloading using macros (simulate)

C Program: Function overloading using macros (simulate)

C

#include <stdio.h>

 

// Macro to simulate function overloading

#define add(...) add_func(__VA_ARGS__, 3, 2, 1)

#define add_func(x, y, z, N, ...) add##N(x, y, z)

 

// Function for single parameter

int add1(int a, int b, int c) {

    return a;

}

 

// Function for two parameters

int add2(int a, int b, int c) {

    return a + b;

}

 

// Function for three parameters

int add3(int a, int b, int c) {

    return a + b + c;

}

 

int main() {

    printf("Sum of one number (5) = %d\n", add(5));

    printf("Sum of two numbers (5, 10) = %d\n", add(5, 10));

    printf("Sum of three numbers (5, 10, 15) = %d\n", add(5, 10, 15));

    return 0;

}

Output

 
OUTPUT 1 :
Addition of int: 15
Addition of double: 7.80
Addition of float: 4.40


Explanation

The macro add(x, y, ...) uses C11's _Generic keyword, which allows you to choose a function based on the type of an expression — effectively simulating function overloading.

  • If the second argument y is of type int → call add_int()
  • If double → call add_double()
  • If float → call add_float()