Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I came across a function definition:

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

What do the three dots mean?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
675 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.
", NULL);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...