Default function parameters

From Tux
Revision as of 19:17, 23 January 2018 by Williams (talk | contribs) (Created page with "Functions that take parameters can also set default values for those parameters that are used if that parameter is not specified. Rules: * You should specify the default para...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Functions that take parameters can also set default values for those parameters that are used if that parameter is not specified.

Rules:

  • You should specify the default parameters in the function prototype, not in the function definition -- otherwise you may get compiler errors
  • Once one parameter has a default value, the remaining parameters (on the right) must also have default parameters
  • When calling the function you must provide parameters for all non-default parameters
  • When you call a function in such a way that a default parameter is used, all remaining default parameters (on the right) must also be used
int fcn(int, int, int = 3, int = 4, int = 5);

int fcn(int a, int b, int c, int d, int e)
{
     return a + b + c + d + e;
}

// The following function calls are valid and return the value given below
fcn(10, 20)                returns 42
fcn(10, 20, 30)            returns 69
fcn(10, 20, 30, 40)        returns 105
fcn(10, 20, 30, 40, 50)    returns 150

// The following function calls are not valid
fcn()
fcn(10);
fcn(10, 20, , 40, 50);