C++

Functions With Default Arguments In C++ – Q&A

When calling a function with no arguments or few arguments, the default arguments are utilized. During program compilation, the default arguments are used. For instance, if you had a user-defined function called sum that was declared as int sum(int a=10, int b=20), and you just called sum() without passing any arguments, the result would be 30 since the compiler had used the default values 10 and 20 that were specified in the function signature. The result would be 100 if only one argument were supplied, utilizing the passed argument’s 80th value as the first value and the default argument’s 20th value as the second.

Example: C++’s default parameters

#include <iostream>
using namespace std;
int sum(int a, int b=10, int c=20);

int main(){
   /* In this case a value is passed as
    * 1 and b and c values are taken from
    * default arguments.
    */
   cout<<sum(1)<<endl;

   /* In this case a value is passed as
    * 1 and b value as 2, value of c values is
    * taken from default arguments.
    */
   cout<<sum(1, 2)<<endl;

   /* In this case all the three values are
    * passed during function call, hence no
    * default arguments have been used.
    */
   cout<<sum(1, 2, 3)<<endl;
   return 0;
}
int sum(int a, int b, int c){
   int z;
   z = a+b+c;
   return z;
}

Output:

31
23
6

Example: C++’s default parameters

As you can see from the example above, I only gave the default values for two arguments—b and c—when I declared the function. It is entirely up to you whether to set default values to all of the arguments or just a few of them, but bear in mind the following guideline:

If you provide an argument a default value, the following arguments also need to have default values given to them; otherwise, a compilation error will occur.

For example: Lets see some valid and invalid cases.
Valid: Following function declarations are valid –

int sum(int a=10, int b=20, int c=30);
int sum(int a, int b=20, int c=30);
int sum(int a, int b, int c=30);

Invalid: Following function declarations are invalid –

/* Since a has default value assigned, all the
 * arguments after a (in this case b and c) must have 
 * default values assigned
 */
int sum(int a=10, int b, int c=30);

/* Since b has default value assigned, all the
 * arguments after b (in this case c) must have 
 * default values assigned
 */
int sum(int a, int b=20, int c);

/* Since a has default value assigned, all the
 * arguments after a (in this case b and c) must have 
 * default values assigned, b has default value but
 * c doesn't have, thats why this is also invalid
 */
int sum(int a=10, int b=20, int c);

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button