Function overloading in C

Written by

Namrata Jangid

What is function overloading?

Function Overloading allows us to have multiple functions with the same name but with different function signatures in our code.

These functions have the same name but they work on different types of arguments and return different types of data.

Therefore, the type of data that is being sent to the function when it is called will determine which function will be called.

Function overloading is a feature of Object Oriented programming languages like Java and C++.

As we know, C is not an Object Oriented programming language.
Therefore, C does not support function overloading.

However, we do have an alternative if at all we want to implement function overloading in C.

We can use the functionality of Function Overloading in C using the _Generic keyword.

_Generic keyword:

We will understand how to use this keyword for Function Overloading using an example.

Let us say that we need an add() function that needs to be overloaded.

This function will return the sum when two digits are passed to it, and it will return a concatenated string if two strings are passed to it.

The code snippet is given below:

  • The add(int x, int y) function accepts two integer type arguments, adds these arguments and returns an integer type value.
  • The adds(char *x, char* y) receives two string literals, concatenates these strings and returns a string literal.
  • The add(a, b) function calls the add(int x, int y) function if it receives two integer type arguments and it calls the adds(char *x, char* y) function if it receives two string literals.

Thus, by using the _Generic keyword, it is possible to achieve Function Overloading in C.

Let us take a look at the main method and the output for the above code snippet:

The output for the first printf() function is 3 and for the second printf() function is
helloworld:

One can also make use of variadic functions for function overloading.

Variadic functions:

Variadic functions can take any number and type of arguments.

Let us look at an example to understand how we can use variadic functions for function overloading in C.
We want to create an add() function which will add any number of arguments passed to it.
The code snippet is given below:

stdarg.h declares a type, va_list, and defines four macros: va_start, va_arg, va_copy,
and va_end. Each invocation of va_start and va_copy must be matched by a
corresponding invocation of va_end.
We are simply looping through the list of arguments sent to the user and adding them.
Let us take a look at the main method and the output for the above code snippet.

The first printf() returns 6 and the second printf() returns 9.

Function overloading in C