Default Arguments in Functions

In C, if a function is defined to receive 2 arguments, whenever we call this function we have to pass 2 values to this function. If we pass one value then some garbage value is assumed for the last argument. As against this, functions in C++ have an ability to define default values for arguments that are not passed when the function call is made. The default arguments are given only in the function prototype and should not be repeated in the function definition. The compiler uses the prototype information to build a call, not the function definition.

Let us illustrate this concept with an example:

Here is an example of a prototype (i.e., function declaration) with default values:

float amount(float principal, int period, float rate = 0.15);

The default value is specified in a manner syntactically similar to the variable initialization. The above prototype declares a default value of 0.15 to the argument rate.

A subsequent function call like:

value = amount(5000, 7);     //one argument missing

passes the value 5000 to principal and 7 to period and then lets the function use the default value of 0.15 for rate.

One more important point to note here is that only the trailing arguments can have default values. That is, we must add defaults from right to left. We cannot provide a default values to a particular argument in the middle of the argument list.

Hence, the prototypes:

float amount(float principal = 5000, int period = 7, float rate);
float amount(float principal = 5000, int period, float rate = 0.15);

are invalid as they does not add defaults from right to left.

You may also like...

Leave a Reply

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