You are on page 1of 7

Functions

Chapter 7
Introduction

• Use of programmer-defined functions allow


modularization
• Advantages
– Avoids the need for redundant programming of the same
instructions
– Logical clarity
– Build a customized library of frequently used libraries
Function
• Self-content program segment
• Carries out its intended action whenever accessed (i.e.
called) from another portion of the program
• Processes information that is passed (via arguments or
parameters) to it from the calling portion of the program
and returns a single value (via return statement)
• Some functions do not return anything (specified by void)
• A C program consists of one or more functions, one of
which must be main()
– Execution of the program always begins from main()
– Others are subroutines to main() or to one another
– Definition of multiple functions may appear in any order, though they
must be independent of one another
– The same function can be accessed from several different places within
a program
Defining a Function
Two principle components:
Assessing a Function
• Means calling it by specifying that name, followed by a
list of arguments enclosed in parentheses
• Arguments appearing in the called function are referred
to as actual parameters
• Value of each actual argument is transferred into the
function and assigned the corresponding formal argument
• Actual arguments must be same as the number of
formal arguments in the function definition
Function Prototype
• Written at the beginning of the program
• Indicates that a define() function will be defined later in
the program
• Arguments within the prototypes are recognised only within
the prototypes
• Function calls can span several levels within a program like
function a calls b, b calls c or function a calls c directly and
so on
Passing Arguments to a Function
• Type value of the corresponding formal argument can be
altered within the function, but the value of the actual
argument within the calling routine will not change.
This is known as passing by values.
• Any alteration to an array element within the function will
carry over the calling routine.
Recursion
• A process by which a function calls itself repeatedly, until
some specific condition is used to terminate it.
• Used for repetitive computation
• To solve a problem recursively, two conditions must be
satisfied:
– The problem must be returned in a recursive from.
– The problem statement must include a stopping condition.
• If a recursive function contains local variables, a different
set of local variables will be created during each call
though the names of the variables will be the same.
Evaluating Recursive Call

You might also like