OOPortal OOPortal
Function/Variable Scope   «Prev  Next»
Lesson 3 Default arguments
Objective Default function arguments can save time in writing C++ program.

C++ Default Function Arguments

A formal parameter can be given a default argument. This is usually a constant that occurs frequently when the function is called. Using a default function argument means that you don't have to declare this default value at each function invocation.

Example


The following function illustrates the point:
//k=2 is default
int sqr_or_power(int n, int k = 2) {
  if (k == 2)
     return (n * n);
  else
    return (sqr_or_power(n, k - 1) * n);
}


We assume that most of time the function is used to return the value of n squared.
sqr_or_power(i + 5)     //computes (i + 5) * (i + 5)
sqr_or_power(i + 5, 3)  //computes (i + 5) cubed

Only the trailing parameters of a function can have default values.