I came across a function definition:
char* abc(char *f, ...) { }
What do the three dots mean?
0 votes. The three dots (...) are used in a function's declaration as a parameter. These dots allow zero to multiple arguments to be passed when the function is called. The three dots are also known as var args.
Followed by one (monadic function) and closely by two arguments (dyadic function). Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.
An ellipsis (plural: ellipses) is a punctuation mark consisting of three dots. Use an ellipsis when omitting a word, phrase, line, paragraph, or more from a quoted passage. Ellipses save space or remove material that is less relevant.
Ellipsis in C++ allows the function to accept an indeterminate number of arguments. It is also known as the variable argument list. Ellipsis tells the compiler to not check the type and number of parameters the function should accept which allows the user to pass the variable argument list.
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); }
Wikipedia on vararg functions in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With