BITS Pilani
K K Birla Goa Campus
CSF111
Computer Programming
Functions
(Supplementary)
Function
• Generic form
• return_type function_name(parameter_list) {
function_body
}
• A function may not have a parameter_list
• A function may not return some value
2
Function Control Flow
void print_banner ()
{ int main ()
printf(“************\n” {
); print_banner {
}
print_banner ();
}
int main () print_banner {
{ print_banner ();
... }
print_banner ();
... }
print_banner ();
} 3
Calling function (Caller)
Function: Looking Deep
• Calling Function
void main()
• Called Function { double cent, fahr;
scanf(“%lf”,¢);
• Parameter
fahr = cent2fahr(cent);
parameter
• Return Value printf(“%lfC = %lfF\n”, cent, fahr);
}
double cent2fahr(double data)
{
double result; Called function (Callee)
Parameter
result = data*9/5 + 32;
passed
return result;
} Calling/Invoking
the cent2fahr function
4
Returning value
Return Statement
In a value-returning function (return type is not void), return does two distinct
things
• specify the value returned by the execution of the function
• terminate that execution of the callee and transfer control back to the
caller
A function can only return one value
• The value can be any expression matching the return type
but it might contain more than one return statement.
In a void function
• return is optional at the end of the function body.
• return may also be used to terminate execution of the function explicitly.
• No return value should appear following return.
5
Function: Parameter Passing
● When the function is executed, the value of the actual
parameter is copied to the formal parameter
parameter passing
int main ()
{ ... double area (double r)
double circum; {
... return (3.14*r*r);
area1 = area(circum);
}
...
}
6
Local Variables
● A function can define its own local variables
● The locals have meaning only within the
function
○ Each execution of the function uses a new set of
locals
○ Local variables cease to exist when the function
returns
● Parameters are also local
7
Local Variables
/* Find the area of a circle with diameter d */
double circle_area (double d)
{ parameter
double radius, area; local
radius = d/2.0; variables
area = 3.14*radius*radius;
return (area);
}
8
Functions: More Points
A function cannot be defined within another
function
• All function definitions must be disjoint
Nested function calls are allowed
• A calls B, B calls C, C calls D, etc.
• The function called last will be the first to return
A function can also call itself, either directly or in a
cycle
• A calls B, B calls C, C calls back A.
• Called recursive call or recursion
9