L6- Functions in C.ppt
L6- Functions in C.ppt
Module-6: Functions in C
Content for the slides have been taken from the various sources and
from the reference books.
• Library Functions
• C has the facility to provide library functions for performing some operations.
These functions are present in the C library and they are predefined.
• For example sqrt() is a mathematical library function which is used for finding
out the square root of any number.
• The functions scanf() and printf( ) are input output library functions.
• Similarly we have functions like strlen(), strcmp() for string manipulation etc.
User Defined Functions
• Users can create their own functions for performing any specific task of the
program.
• These types of functions are called user-defined functions.
• To create and use these functions, we should know about these three things-
• 1. Function definition
• 2. Function declaration
• 3. Function call
Function Definition
• The function definition consists of the whole description and code (of a
function.
• It tells what the function is doing and what are its inputs and outputs.
• A function definition consists of two parts - a function header and a function
body.
• The general syntax of a function definition is
• return_type func_name (typel argl, type2 arg2, …..)
{
local variables declarations;
statement;
…….
return(expression) ;
}
Function Definition
• The first line in the function definition is known as the function header and
after this the body of the function is written enclosed in curly braces.
• The return_type denotes the type of the value that will be returned by the
function.
• The return_type is optional and if omitted, it is assumed to be int by default.
• A function can return. either one value or no value.
• If a function does not return any value then void should be written in place of
return_type.
• func_name specifies the name of the function and it can be any valid C
identifier.
• After function name the argument declaration are given in parentheses, which
mention the type and name of the arguments.
• These are known as formal argument and used to accept values.
• A function can take any number 0 arguments or even no argument at all.
Function Definition
• If there are no arguments then either the parentheses can be left empty or void
can be written inside the parentheses.
• The body of function is a compound statement (or a block), which consists of
declarations of variables and C statements followed by an optional return
statement.
• The variables declared inside the function are known as local variables, since
they are local to that function only, i.e. they have existence only in the function
in which they are declared, they can not be used anywhere else in the program.
• There can be any number of valid C statements inside a function body.
• The return statement is optional. It may be absent if the function does not
return any value.
• The function definition can be placed anywhere in the program.
• But generally all definitions are place after the main () function.
• Note that a function definition cannot be placed inside another function
definition.
Function Definition
Function Call
• The function definition describes what a function can do, but to actually use it
in the program the function should be called somewhere.
• A function is called by simply writing its name followed by the argument list
inside the parentheses.
func_nam(arg1, arg2, arg3 ...)
• These arguments arg1, arg2, ,... are called actual arguments..
• Here func_name is known as the called function while the function in which
this function call is placed is known as the calling function.
• The function call is written on the right hand side of the assignment operator
as-
s = sum(a, b);
• Even if there are no actual arguments, the function call should have the empty
parentheses, For example the function call can be written as
drawline( );
Function Call
• When a function is called, the control passes to the called function, which is
executed and after this the control is transferred to the statement following the
function call in the calling function.
• The following figure shows the transfer of control when two functions func1( )
and func2( ) are called from main()
Function Call
Function Declaration
• The calling function needs information about the called function.
• If definition of the called function placed before the calling function, then
declaration is not needed.
Function Declaration
• Here the definition of sum() is written before main(), so main() knows
everything about the function sum().
• But generally the function main() is placed at the top and all other functions
are placed after it.
• In this case, function declaration is needed. The function declaration is also
known as the function prototype, .and it informs the compiler about the
following three things-
• 1. Name of the function
• 2. Number and type of arguments received by the function.
• 3. Type of value returned by the function,.
• Function declaration tells the compiler that a function with these features will
be defined and used later in the program.
• The general syntax of a function declaration is- . ,
• return_type func_name(type1 arg1, type2 arg2, .. ,.....)
Function Declaration
• Program that finds whether a number is even or odd
Return type
Return type
• Some other examples of valid return statements are
• return 1;
• return x++;
• return ( x+y*'z );
• return (3*sum(a, b));
• It is optional to enclose the returning value in parentheses.
• We can use multiple return statements in a function but as soon as
first return statement is encountered the function terminates and all
the statements following it are not executed.
•
Function Arguments
• The calling function sends some values to the called function for
communication; these values are called arguments or parameters.
• Actual arguments: The arguments which are mentioned in the function call
are known as actual arguments, since these are the values which are actually
sent to the called function. Actual arguments can be written in the form of
variables, constants or expressions or any function call that returns a value.
• For example-
• fun(x,)
• func.(a*b, c*d+k)
• . func( 22, 43 )
• func(1, 2, sum(a, b) )
Function Arguments
• Formal arguments: The name of the arguments, which are mentioned in the
function definition are called formal or dummy arguments since they are
used just to hold the values that are sent by the calling function.
• These, formal arguments are simply like other local variables of the function
which are created when the function call starts and are destroyed when the
function ends. However there are two differences,
• First is that formal arguments are declared inside parentheses while other
local variables are declared at the beginning of the function block.
• The second difference is that formal arguments are automatically initialized
with the values of the actual arguments passed, while other local variables
are assigned values through the statements written inside the function body.
• The order, number and type of actual arguments in the function call should
match with the order, number and type of formal arguments in the function
definition.
Types Of Functions
• The functions can be classified into four categories on the basis of the
arguments and return value.
• 1. Functions with no arguments and no return value.
• 2. Functions with no arguments and a return value.
• 3. Functions with arguments and no return value.
• 4. Functions with arguments and a return value
• void func(void)
• The function func() has no arguments, main() can not send any data to func()
and since it has no return statement, hence function can not return any value
to main().
• There is no communication between the calling and the called function.
Function With No Arguments But A Return Value
Function With Arguments But No Return Value
• These types of functions have arguments, hence the calling function can send
data to the called function but the called function does not return any value.
Function With Arguments And Return Value
• These types of functions have arguments, so the calling function can send
data to the called function, it can also return any value to the calling function
using return statement.
If Declaration Is Absent
Order of Evaluation Of Function Arguments
• When a function is called with more than one argument then the order of
evaluation of arguments is unspecified.
• This order of evaluation is not important in function calls like multiply(m,n)
or multiply(m+n, m-n).
• But if we have a function call like this:
int m = 3, k;
k = multiply( m, m++);
• Now here if the first argument is evaluated first then value of k will be 9, and
if the second argument is evaluated first, the value of k will be 12. But since
the order of evaluation of arguments is unspecified in C and depends on
compiler, hence the result may be different on different compilers.
Order of Evaluation Of Function Arguments
• When a function is called with more than one argument then the order of
evaluation of arguments is unspecified.
• This order of evaluation is not important in function calls like multiply(m,n)
or multiply(m+n, m-n).
• But if we have a function call like this:
int m = 3, k;
k = multiply( m, m++);
• Now here if the first argument is evaluated first then value of k will be 9, and
if the second argument is evaluated first, the value of k will be 12. But since
the order of evaluation of arguments is unspecified in C and depends on
compiler, hence the result may be different on different compilers.
Function Call and Stack
• To understand how C performs function calls, we need to
consider a data structure known as a stack.
• Think of a stack as analogous to a pile of dishes.
• When a dish is placed on the pile, it’s normally placed at the
top (pushing onto the stack).
• When a dish is removed from the pile, it’s normally removed
from the top (popping off the stack).
• Stacks are known as last-in, first-out (LIFO) data
structures—the last item pushed (inserted) on the stack is the
first item popped (removed).
Function Call and Stack
Function Call and Stack
Function Call and Stack
Function Call and Stack
Call by Value and Call by Reference
• Whenever we called a function and passed something to it we have
always passed the ‘values’ of variables to the called function. Such
function calls are called ‘calls by value’.
• By this what we mean is, on calling a function we are passing values
of variables to it. The examples of call by value are shown below:
• sum = calsum(a, b, c) ;
• f = factr (a) ;
• We have also learnt that variables are stored somewhere in memory.
• So instead of passing the value of a variable, can we not pass the
location number (also called address) of the variable to a function? If
we were able to do so it would become a ‘call by reference’.
Local, Global And Static Variables
• Local Variables
• The variables that are defined within the body of a function or a
block, are local to that function block only and are called local
variables.
• For example
func ()
{
int_ a, b;
…..
}
• Here a and b are local variables which are defined within the body of
the function func(). Local variable can be used only in those functions
or blocks, in which they are declared.
Local, Global And Static Variables
• The same variable may be used in different functions.
• For example
func1()
{
int a=2,b=4;
…..
}
func2()
{
int a=15,b=20;
….
}
• Here values of a = 2, b = 4 are local to the function funcl() and a = 15,
b = 20 are local to the function func2().
Global Variables
• The variables that are defined outside any function are called global
variables.
• All functions in the program access and modify global variables.
• It is useful to declare a variable global if it is to be used by many
functions in the program.
• Global variables are automatically initialized to 0 at the time of
declaration.
Global Variables
Global Variables
• Here a and b are declared outside all functions hence; they
are global variables.
• The variable a will be initialized to 0 automatically since it is
a global variable.
• Now we can use these variables in any function.
• func2( ), there is local variable with the same name as global
variable.
• Whenever there is a conflict between a local and global
variable, the local variable gets the precedence.
• So inside func2() the value of local variable gets printed
Static Variables
• Static variables are declared by writing keyword static in front of
the declaration.
Output
84
Passing arrays to functions
Output
Result = 162.50
Passing two-dimensional arrays
Passing arrays to functions
• To pass an entire array to a function, only the name of the array is passed as an
argument.
• result = calculateSum(age);
• However, notice the use of [] in the function definition.
• This informs the compiler that you are passing a one-dimensional array to the
function.
Recursion
• Recursion is a powerful technique of writing a complicated algorithm
in an easy way.
• According to this technique a problem is defined in terms of itself.
• The problem is solved by dividing it into sub-problems, which are
similar in nature to the original problem.
• These smaller problems are solved their solutions are applied to get
the final solution of our original problem.
• To implement recursion technique in programming, a function should
be capable of calling itself.
• The function that calls itself inside function body again and again is
• Called a recursive function.
• In recursion the calling function and the called function are same.
Recursion
main ()
{
…..
rec () ;
…..
}
rec()
{
…..
rec (); //recursive call
}
•Here rec() is called inside the body of function rec().
•There should be a terminating condition to stop recursion, otherwise rec() will
keep on calling itself infinitely and will never return.
Recursion
• The use of recursion makes the code more compact and elegant.
• It simplifies the logic and hence makes the program easier to
understand.
• But the code written using recursion is less efficient since
recursion is a slow process because of many function calls
involved in it.
• Most problems with recursive solutions also have an equivalent
non-recursive(generally iterative) solutions.
• A non recursive solution increases performance while a
recursive solution is simpler.
Local Variables In Recursion
• We know each function has some local variables that exist only
inside that function.
• When a function is called recursively, then for each call a new
set of local variables is created(except static), their name is
same but they are stored at different places and contain different
values.
• These values are remembered by the compiler till the end of
function call, so that these values are available in the unwinding
phase.
Thank you for your attention!
< Questions?