Returning a value to the calling function:
We can send data from calling function to the called by
function using arguments or parameters.
The called by function is capable to send back a single
value to the calling function.
"return" is a statement used to return a single
vale to the calling function.
"return" statement is also used to terminate the
execution of a function.
Example:
Output:
Sum=50
Example explained:
The values of x, y (actual arguments) are assigned to p, q
(formal arguments).
Sum of two numbers (r) is returned to calling function and
assigned to "z".
Value of "z" (50) is printed as sum.
Working with other types (other than integers):
By default C compiler considers arguments and return value
as integers.
If we use other types as arguments and return value then function
declaration and return type must be specified otherwise it results error.
Example:
#include<stdio.h>
void main()
{
float x,y,z;
clrscr();
x=12.45;
y=25.15;
z=adding(x,y);
printf("Sum=%f",z);
getch();
}
adding(float p,float q)
{
float r;
r=p+q;
return r;
}
Output:
Error: Floating point error: Domain
Example explained:
By default C compiler considers arguments and return type as
integers.
It has given error because arguments and return value are of
floating point types.
We can rectify the program by specifying the return type and
declaration.
Example rectified:
Output:
Sum=37.599998
Putting all together:
Function is a self-contained block of code that performs a
particular task.
It helps to follow modular approach in developing
applications.
It helps to reduce development time.
It promotes reusability.
Defining and using of any function required three things.
- Function
definition.
- Function
calling statement.
- Function
declaration.
Function definition:
Any function has a name which must be a valid identifier.
List of formal arguments are defined, the values of which
are assigned by the actual arguments of calling statement.
Body of the function is defined with in { }
"return" is the statement used to return maximum a
single value to the calling function.
"return" is also used to terminate the execution
of a function.
Return type is specified if the function returns a
non-integer. At least void must be specified if a function doesn't return any
value.
Syntax: <return
type> <name>( <List of formal arguments> ) { ---------------- ---------------- return <exp>; ---------------- ---------------- } Example: int
adding(int x, int y) { return x+y; } (or) int
adding(x,y) int x,y; {
return x+y; }
0 comments:
Post a Comment