Skip to content

Instantly share code, notes, and snippets.

@koraysaritas
Forked from barosl/add.c
Created April 27, 2017 10:46
Show Gist options
  • Save koraysaritas/bcb0f5cb2d5108a391e4f87cd6597a67 to your computer and use it in GitHub Desktop.
Save koraysaritas/bcb0f5cb2d5108a391e4f87cd6597a67 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment