Question about a function definition (three dots in parameters..)

前端 未结 4 1958
生来不讨喜
生来不讨喜 2020-12-07 18:47

I came across a function definition:

char* abc(char *f, ...)
{
}

What do the three dots mean?

相关标签:
4条回答
  • 2020-12-07 19:02

    They are called an elipsis and they mean that the function can take an indeterminate number of parameters. Your function can probably be called like this:

    abc( "foo", 0 );
    abc( "foo", "bar", 0 );
    

    There needs to be a way of indicating the end of the list. This can be done by using the first parameter, as ion a printf(0 format string, or by a special terminator, zero in the example above.

    Functions with a variable number of parameters are considered bad form in C++, as no type checking or user defined conversions can be performed on the parameters.

    0 讨论(0)
  • 2020-12-07 19:10

    Wikipedia on vararg functions in C++.

    0 讨论(0)
  • 2020-12-07 19:13

    This is what is called a varargs function or a variable argument function in C.

    One you'll probably recognise is printf.

    0 讨论(0)
  • 2020-12-07 19:14

    These type of functions are called variadic functions (Wikipedia link). They use ellipses (i.e., three dots) to indicate that there is a variable number of arguments that the function can process. One place you've probably used such functions (perhaps without realising) is with the various printf functions, for example (from the ISO standard):

    int printf(const char * restrict format, ...);
    

    The ellipses allow you to create functions where the number of parameters are not known beforehand, and you can use stdargs.h functions (va_start, va_arg and va_end) to get the specific arguments.

    You do have to know the types of the arguments you extract and have some way of deciding when you're done. The printf functions do this with the format string (for both types and count), while my example code below always assumes const char * as the type with a sentinel value NULL to decide completion.

    This link here has a good treatise on the use of variable argument lists in printf.


    As an example, the following program contains a function outStrings(), that allows you to print an arbitrary number of strings:

    #include <stdio.h>
    #include <stdarg.h>
    
    void outStrings(const char *strFirst, ...) {
        // First argument handled specially.
    
        printf("%s", strFirst);
        va_list pArg;
        va_start(pArg, strFirst);
    
        // Just get and process each string until NULL given.
    
        const char *strNext = va_arg(pArg, const char *);
        while (strNext != NULL) {
            printf("%s", strNext);
            strNext = va_arg(pArg, const char *);
        }
    
        // Finalise processing.
    
        va_end(pArg);
    }
    
    int main(void) {
        char *name = "paxdiablo";
        outStrings("Hello, ", name, ", I hope you're feeling well today.\n", NULL);
    }
    
    0 讨论(0)
提交回复
热议问题