Functions.....cont(2)

Default Values in Arguments

When defining a function we can specify default values that will be taken into acount by the argument variables in case these are avoided when the function is called. This is done by simply assigning a value to the arguments when declaring the function. These values will be used if that parameter is not passed when when the function is called. If the value of that parameter is finally set when calling the dafault value, it is stepped up. For eg:

// default values in functions Output

#include<iostream.h> 6

int divide(int a, int b=2) 5

{

int r;

r=a/b;

return (r);

}

int main()

{

cout<divide(12);

cout<<endl;

cout<<divide(20,4);

return 0;

}

Constant Arguments

Constant arguments, cannot be modified by a functio. If constant arguments are passed to the function, then the function cannot modify these values.

For eg, the function call:

mult(3,5);

cannot modify its arguments as 3 and 4 are constant values.

An argument to a function can be made constant, using the keyword const as shown below:

int add(const int x, const int y);

the qualifier const in the function prototype notifies the compiler that the function should not alter the values of the argument. Constant arguments are useful when functions are called by reference.

Returning from a function

Returning from a function not only terminates the function's execution but also passes the control back to the calling function. Hence it is very important. The function execution terminates if a return statement is encountered or the last statement in the function gets executed. Generally, a return statement is used to terminate a function wheter or not it returns a value.

The Return Statement

The return statement is used in order to exit from the function and to bring the program control back to the calling function. A return statment is used in the function main to give the control back to teh operating system. Although a return statement is not essential, most of the functions use it to stop execution of a program.

Returning values from Functions

All functions return a value, except those of type void. This value is clearly specified by the return statement. If a function doesn't contain a return statement its return value is undefined.

A function of return type void does not return a value and hence cannot be used in expressions.

HOME LEARN C++ PREVIOUS NEXT