Computer Science: Function: Function with Default Arguments

Get unlimited access to the best preparation resource for CBSE/Class-8 Science: fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 290K)

Image of default arguments

Image of Default Arguments

Image of default arguments

Function with Default Argument

  • C ++ allows to call a function without specifying all its arguments.

  • In such cases, the function assigns a default value to a parameter which does not have a matching argument in the function call.

  • The compiler knows from the prototype how many arguments a function uses for calling.

Example

float result (int marks 1, int marks 2, int marks 3 = 75).

A subsequent function calls

Average = result (60, 70).

  • Passes the value 60 to marks 1, 70 to marks 2 and lets the function use default value of 75 for marks3.

  • The call Average = result (60, 70, 80).

  • Passes the value 80 to marks 3.

  • The important point to note is that only the trailing argument can have default values.

Consider the following program:

# include < iostream.h>

void repchar (char = ‘=’, int = 30).

void main ()

{

repchar ().

repchar ;

repchar (‘+’, 45).

}

void repchar (char ch, int x)

{

for (int i= 1; i < = x; i + +)

cout < < ch.

cout < < “\n”.

}

The default argument follows an equal sign, which is placed directly after the type name.

In the above program, the function repchar () takes two arguments. It is called three times from main ().

  • First time it is called with no argument. The function assigns the default value ‘=’ to ch and 30 to x and it print ‘=’ symbol thirty times on the screen.

  • Second time it is called with one argument. The function assigns the default value 30 to x and it prints ‘*’ symbol thirty times on the screen.

  • Third time it is called with two arguments. The actual parameters take priority over the default parameters. It prints ‘+’ symbol forty-five times.

Developed by: