Variable arguments to a function in any language gives us a flexibility while calling the function. The number of arguments to a function are not fixed, and a number of calls can be made to the same function which would otherwise have been impossible without method overloading.
Consider the following example:
You have to write an add function that adds the values of the arguments given to it and returns the sum.
You can possibly achieve this in the following ways:
The first method allows only 2 numbers to be added. If you want to add 3 numbers you cannot use this function. You will have to define another overloaded function.
The second method allows a variable number of numbers to be added. However, whenever you call it, a new int array needs to be defined:
and so on.
In comes the variable arguments to save the day.
Typical Issues with varargs,
- Only one variable argument can be present per method.
- Typically, you can mix it with fixed arguments, however, the variable argument has to be at the end in the function parameter list.