1.

Explain passing default argument to the function with an example. 

Answer»

When we define a function, we can specify a default value for each of the parameters. This value will be used if the corresponding argument is left blank during function call to the called function.

This is done by using the assignment operator and assigning values for the arguments in the function definition. During the function call, if a value for that parameter is not passed then default value is used, but if a value is mentioned then this default value is ignored and the passed value is used.

Consider the following example:

#include<iostream>

int sum (int a,int b = 20)

{

int result;

result = a + b;

return(result);

}

int main()

{

//local variable declaration:

int x = 100;

int t = 200;

int result;

//calling a function to add the values.

result = sum(x,y);

cout<<"Total value is :'<<result<<endl;

//calling a function again as follows.

result = sum(x);

cout<<"Total value is :'<<result<<endl;

return 0;

}

In the above program, the statement int sum(int a, int b=20) in the function header indicates the v default argument to the variable b is assigned with the value 20. During the first function call, the statement result = sum(x, y); copies the value of x and y to the called function and process of the result. 

During second time function call i.e., result = sum(x);, only one argument is mentioned and the value for second argument is obtained from the default argument which is mentioned in the function definition i.e., b=20 and gives the processed result.



Discussion

No Comment Found

Related InterviewSolutions