How to achieve function overloading in C?

前端 未结 14 2518
清歌不尽
清歌不尽 2020-11-22 03:16

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         


        
相关标签:
14条回答
  • 2020-11-22 04:20

    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

    0 讨论(0)
  • 2020-11-22 04:22

    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.

    0 讨论(0)
提交回复
热议问题