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. By default, functions can only take a fixed number of parameters that are known to the function beforehand. The user cannot pass a variable number of arguments.
Below is the code that gives compilation error:
max() function can take only 2 arguments. So when 4 arguments were used to it in the function call, the compiler threw an error. However, there may be some situations a function has to take a variable number of arguments.
We can pass number of arguments using Ellipsis. It is defined under the cstdarg header file. Ellipsis is not a keyword rather it is denoted by ‘…’ sign.
Below is the program to illustrate the use of Ellipsis:
Average is 3.5
Here, average() takes six arguments and calculates the average. Let us see how it works.
- va_list type is used to access the values in the ellipsis. It will be conceptually easy for you if you think of ellipsis as an array. In that case, va_list will act as the iterator type. The va_list is not a special type. It is a macro definition.
- va_start points to the va_list at the starting point of the ellipsis. It takes two arguments: va_list itself and the last normal parameter (non-ellipsis).
- va_arg returns the value which va_list is currently referring to and also moves va_list to the next parameter. It also takes two arguments: va_list itself and the type of the parameter we are trying to access.
- va_end takes only one argument: va_list itself. It is used to clean up the va_list macro.
Though ellipsis gives us some useful functionality, it is quite dangerous to use them. When using ellipsis, the compiler does not check the type of arguments passed to the function. So the compiler does not throw any error if arguments are of different types. Even if pass string, double, or bool type values are passed to the average() function it returns return an unexpected value, the compiler does not throw any error.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.