Create a C function that accepts parameters of different data types

前端 未结 6 1280
陌清茗
陌清茗 2021-02-09 02:07

I\'m relatively new to the C programming language, and I\'m trying to figure out how to create a function that can accept different types of data as parameters. The function is

6条回答
  •  心在旅途
    2021-02-09 02:48

    There is no standard function overloading in C (nor are there templates), but you could probably look into "printf-like" functions (or variadic functions) and maybe they can do what you need. If anything they allow for a flexible parameter list.

    There is an example here of such a function that takes a variable size integer array.

    Perhaps you could have a function signature such as void iterate(const char* format, ...); that you use in the following ways:

    iterate("char", some_char_array); // for char arrays/strings
    

    Or

    iterate("int", some_int_array); // for integer arrays
    

    Aniket makes a good point though, how do you count the elements in an integer array? If you pass an int array as an argument, you would need to pass the size too which defeats the purpose of counting the elements in the array (as you already know that i.e. the size).

    I assume you don't know the size but you have a terminator value in the array (such as -1).

    I've hacked something quick that kinda does what you need with the above assumption in mind.

    #include 
    #include 
    #include 
     
    int iterate(const char* format, ...)
    {
        va_list ap;
        va_start(ap, format);
    
        if (strcmp(format, "char") == 0)
        {
            char* array = va_arg(ap, char*);
    
            va_end(ap);
            return strlen(array);
        }
        else if (strcmp(format, "int") == 0)
        {
            int j = -1;
            int* int_array = va_arg(ap, int*);
            while (int_array[++j] != -1)
                        ;   
            va_end(ap);  
            return j;
        }
        va_end(ap);
        return 0;
    }
    
    int main()
    {
        printf("%d\n", iterate("char", "abcdef"));
        int arr[] = {5, 4, 3, 2, 1, 0, -1};
        printf("%d\n", iterate("int", arr));
    
        return 0;
    }
    

    This prints:

    $ ./a.out 
    6
    6
    

提交回复
热议问题