Is there any way to achieve function overloading in C? I am looking at simple functions to be overloaded like
foo (int a)
foo (char b)
foo (float c , i
Here is the clearest and most concise example I've found demonstrating function overloading in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int addi(int a, int b) {
return a + b;
}
char *adds(char *a, char *b) {
char *res = malloc(strlen(a) + strlen(b) + 1);
strcpy(res, a);
strcat(res, b);
return res;
}
#define add(a, b) _Generic(a, int: addi, char*: adds)(a, b)
int main(void) {
int a = 1, b = 2;
printf("%d\n", add(a, b)); // 3
char *c = "hello ", *d = "world";
printf("%s\n", add(c, d)); // hello world
return 0;
}
https://gist.github.com/barosl/e0af4a92b2b8cabd05a7
In the sense you mean — no, you cannot.
You can declare a va_arg
function like
void my_func(char* format, ...);
, but you'll need to pass some kind of information about number of variables and their types in the first argument — like printf()
does.