Skip to the content of the web site.

Lesson 1.31: Default values of parameters

Up to this point, the programmer using a function must supply arguments for each of the parameters. There are some circumstances, however, where certain parameters may have natural default values, and thus, requiring the programmer to specify each of these arguments may be tedious or burdumsome.

As an example, suppose that an author wrote a function to approximate the sine of a real number. The argument could be in degrees or radians. While the second is the natural choice, some users may want to specify the angle in degrees.

double fast_sin( double x, bool use_degrees );

double fast_sin( double x, bool use_degrees ) {
    // 
    double radians_per_degree{ 0.017453292519943296 };
    double pi_by_two{ 0.017453292519943296 };

    // If the argument is in degrees,
    // convert the degrees to radians.
    if ( use_degrees ) {
        x *= radians_per_degree;
    }

    assert( (x >= 0) && (x <= pi_by_two) );

    // Approximate sin(x) for 0 <= x <= pi/2
    return ((
        -0.11073981636184074*x - 0.057385341027109429
    )*x + 1.0)*x;
}

However, most users will call this function assuming the argument is in radians, so these function calls will always be:

    double points[65];

    for ( std::size_t k{0}; k <= 64; ++ k ) {
        points[k] = fast_sin( 0.015625*k, false );
    }

The author of the function may, however, assign a default value to the second parameter by using the equal sign in the function declaration:

double fast_sin( double x, bool use_degrees = false );

double fast_sin( double x, bool use_degrees ) {
    // Function body...
}

It is important that the default value can only be assigned in the function declaration, and never in the function definition. It is not even possible to repeat the default value in the function defintion.