Chapter-9
User-defined Functions
Copyright © 2016 McGraw Hill Education, All Rights Reserved.
PROPRIETARY MATERIAL © 2016 The McGraw Hill Education, Inc. All rights reserved. No part of this PowerPoint slide may be displayed, reproduced
or distributed in any form or by any means, without the prior written permission of the publisher, or used beyond the limited distribution to teachers and
educators permitted by McGraw Hill for their individual course preparation. If you are a student using this PowerPoint slide, you are using it without
permission.
Introduction
• C functions can be classified into two categories-
• Library functions: Library functions are pre-defined functions
and are not required to be written by user.
• e.g: printf, scanf, sqrt, cos
• User-defined functions: User-defined functions has to be
developed by the user at the time of writing a program.
• e.g: main
Need for User-defined functions
• Utilizing only main function leads to a problem of- program too large,
complex, task of debugging, testing and maintaining becomes
difficult.
• If a program is divided into functional parts, then each part may be
independently coded and later combined into a single unit called
subprograms that are much easier to understand, debug and test.
• In C, such subprograms are referred to as functions.
• Sometimes, program statement may need to be repeated multiple
times in a program, a function can be design and can be called and
used whenever required.
Advantages of functions
• It facilitates top-down modular programming. The high-level logic of
the overall problem is solved first while the details of each lower-level
function are addressed later.
• The length of a source program can be reduced by using functions at
appropriate places.
• It is easy to locate and isolate a faulty function for further
investigations.
• A function may be used by many other programs.
Fig. 9.1 Top-down modular programming using functions
A Multi-Function Program
• A function is a self-contained block of code that performs a particular
task.
• Once a function has been designed and packed, it can be treated as
a black-box that takes some data from the main program and returns
a value.
• The inner details of operation are invisible to the rest of the program.
• Every C program can be designed using a collection of functions.
void printline (void)
{
int I;
for(i=1;i<40;i++)
printf(“ - ”);
prinft(“\n”);
}
Fig. 9.2 Flow of control in a multi-function program
Modular Programming
• Modular programming is a strategy applied to the design and
development of software systems.
• It is defined as organizing a large program into small, independent
program segments called modules that are separately named and
individually callable program units.
• Characteristics of modular programming are:
• Each module should do only one thing.
• Communication between modules is allowed only by a calling
module.
• A module can be called by one and only one higher module.
• No communication can take place directly between modules that
do not have calling-called relationship.
• All modules are designed as single-entry, single-exit systems
using control structures.
• Both function names and variable names are considered identifiers
and therefore they must adhere to the rules for identifiers.
• Like variables, functions have types (such as int) associated with
them.
• Like variables, function names and their types must be declared and
defined before they are used in a program.
Elements of User-Defined Functions
• Three elements of functions are:-
• Function definitions: is an independent program module that is
specially written to implement the requirements of the function.
• In order to use the function, we need to invoke it at a required
place in the program. This is known as function call.
• The program (or the function) that calls the function is referred to
as the calling program or calling function.
• The program should declare any function (like declaration of a
variable) that is to be used later in the program. This is known as
the function declaration or function prototype.
Definition of functions
• A function definition also known as function implementation shall
include the following elements:
• function header
• function name
• function type
• list of parameters
• function body
• local variable declarations
• function statements, and
• a return statement
• function_type function_name (parameter list) // function header
{
local variable declaration;
executable statement1;
executable statement2;
…….
…….
return statement;
}
Function Header
• It consists of three parts: the function type (also known as return
type), the function name and the formal parameter list.
• Semicolon is not used at the end of the function header.
Name and Type
• function type specifies the type of value (like float or double) that the
function is expected to return to the program calling the function.
• If the function is not returning anything, return type is specified as
void.
• function name is any valid C identifier and follow the same rules of
formation as other variables name in C.
Formal Parameter List
• It declares the variables that will receive the data sent by the calling
program. It serve as input data to the function.
• e.g.: float quadratic(int a, int b, int c) {….}
int sum(int a, int b) {….}
Function body
• function body contains the declarations and statement necessary for
performing the required task. It contains three parts:
• Local declarations- specify variables needed by the function
• Function statements- perform the task of the function
• A return statement that returns the value evaluated by the
function.
• If function not return value, return statement can be omitted.
• Example of function definition:
• float mul(float x, float y){
• float result; //local variable
• result = x *y; //computes product
• return (result); //returns result
• }
Return values and their Types
• A function may or may not send back any value to the calling
function.
• If it return, it is done through the return statement.
• It is possible to pass to the called function any number of values, the
called function can only return one value per call, at the most.
• The return statement takes the form:
return;
or
return (expression);
• When a return is encountered, the control is immediately passed
back to the calling function.
• When a value is returned, it is automatically cast to the function’s
type.
Examples
• if (error)
return;
• int mul (int x, int y){
int p;
p = x * y; | or, return (x*y);
return (p); |
}
• if(x <= 0)
return (0);
else
return (1);
Function Calls
• A function can be called by simply using the function name followed
by a list of actual parameters (or arguments), if any, enclosed in
parentheses.
• Example:
main(){
int y;
y = mul (10, 5); //function call
printf(“%d\n”, y);
} int mul (int x, int y){
int p; //local variable
p = x*y; //x=10, y=5
return (p);
}
• Different ways to call a function:
o mul (10, 5)
o mul (m, 5)
o mul (10, n)
o mul (m, n)
o mul (m+5, 10)
o mul (10, mul(m,n))
o mul (expression1, expression2)
printf(“%d\n”, mul(p,q)); valid
y = mul(p,q) / (p+q) valid
if (mul(m,n)>total) printf(“large”); valid
mul(a,b) = 15 Invalid
• A function call is a postfix expression.
• If the actual parameter are more than the formal parameter, the extra
actual arguments will be discarded.
• If the actuals are less than the formals, the unmatched formal
arguments will be initialized to some garbage.
• Any mismatch in data types may also result in some garbage values.
Function Declaration
• Like variables, all functions in a C program must be declared before
they are invoked.
• A function declaration consists of four parts-
• Function type (return type).
• Function name.
• Parameter list.
• Terminating semicolon.
• Format: function-type function-name(parameter list)
• It is similar to the function header line except the terminating
semicolon.
To Remember
• The parameter list must be separated by commas.
• The parameter names do not need to be the same in the prototype
declaration and the function definition.
• The types must match the types of parameters in the function
definition, in number and order.
• Use of parameter names in the declaration is optional.
• If the function has no formal parameters, the list is written as (void).
• The return type is optional, when the function returns int type data.
• The return type must be void if no value is returned.
• When the declared types do not match with the types in the function
definition, compiler will produce an error.
mul function declaration-
• int mul (int, int);
• mul (int a, int b);
• mul (int, int);
• When a function does not take any parameters and does not return
any value, its prototype is written as:
• void display (void);
• A prototype declaration may be placed in-
• Above all the functions (including main) – Global prototype
• Inside the function definition – Local prototype
Parameters
• Parameters (also known as arguments) are used in:
• declaration (prototypes) - called formal parameters
• function call - called actual parameters
• function definition - called formal parameters
• The formal and actual parameters must match exactly in type, order
and number.
• Names do not need to match.
Category of Functions
• Category 1: Functions with no arguments and no return values.
• Category 2: Functions with arguments and no return values.
• Category 3: Functions with arguments and one return value.
• Category 4: Functions with no arguments but return a value.
• Category 5: Functions that return multiple values.
No arguments and no return values
Fig. 9.3 No data communication between functions
(Contd.)
Fig. 9.4 Functions with no arguments and no return values
Arguments But No Return Values
Fig. 9.5 One-way data communication
Fig. 9.6 Arguments matching between the function call and the called function
(Contd.)
Fig. 9.7 Functions with
arguments but no return
values
Arguments with Return Values
Fig. 9.8 Two-way data communication between functions
(Contd.)
Fig. 9.9 Functions with arguments and return values
Returning float values
• When a function returns float or double (i.e. other than int), we must
explicitly specify the return type in both the function definition and the
prototype declaration.
• Mismatch between type of data that the called function returns and
the type of data that the calling function expects, it leads to
unpredictable results.
(Contd.)
Fig. 9.10 Power fuctions: Illustration of return of float values
Functions that return multiple values
• To get more information from a function, arguments can also be used
to send back information to the calling function.
• The mechanism of sending back information through arguments is
achieved using address operator (&) and indirect operator (*).
• The use of pointer variables as actual parameter for communicating
data between functions is called “”
Nesting of Functions
• C permits nesting of functions freely. No limit. p = mul(mul(5,2),6) is also valid
• E.g.
float ratio (int x, int y, int z);
int difference (int x, int y);
int main(void){
int a, b, c;
scanf(“%d%d%d”,&a, &b, &c);
printf(“%f\n”, ratio(a,b,c));
}
float ratio(int x, int y, int z){ int difference(int p, int q){
if(difference(y,z)) if(p!=q)
return(x/(y-z)); return 1;
else
else
return 0;
return (0.0); }
}
Recursion
• When a called function in turn calls another function a process of
‘chaining’ occurs. Recursion is a special case of this process, where
a function calls itself.
• E.g.
int main(void){
printf(“This is an example of recursion \n”);
main();
}
• Function to evaluate factorial of n-
factorial (int n)
{
int fact;
if (n==1)
return 1;
else
fact = n * factorial(n-1);
return(fact);
}
• Recursive functions can be effectively used to solve problems where
solution is expressed in term of successively applying the same
solution to subsets of the problem.
Passing Array to Functions
• One-Dimensional Arrays-
• To pass a one-dimensional array to a called function, it is
sufficient to list the name of the array, without any subscripts and
the size of the array as arguments.
• E.g. largest (a,n) will pass the whole array a to the called
function.
• largest function definition header-
• float largest(float array[ ], int size)
• In C, the name of the array represents the address of its first element.
• By passing the array name, we are passing the address of the array
to the called function.
• The array in the called function now refers to the same array stored in
the memory.
Fig. 9.11 Passing of arrays to a function
Three Rules to Pass an Array to as Function
• The function must be called by passing only the name of the array.
• In the function definition, the formal parameter must be an array type;
the size of the array does not need to be specified.
• The function prototype must show that the argument is an array.
Fig. 9.12 Sorting of array
elements using a function
• Two-Dimensional Array-
• The function must be called by passing only the array name.
• In the function definition, we must indicate that the array has two-
dimensions by including two sets of brackets.
• The size of the second dimension must be specified.
• The prototype declaration should be similar to the function
header.
int main(void){
int m=3, n=2;
double average (int [ ] [n], int, int);
double mean;
int matrix[m][n]= { {1,2}, {3,4}, {5,6}};
mean = average (matrix, m, n);
……..
}
double average(int x[ ] [n], int m, int n){
int i, j;
double sum=0.0;
for(i=0; i<m; i++)
for(j=1; j<n; j++)
sum += x[i] [j];
return(sum/(m*n));
}
Passing Strings to functions
• The strings are treated as character arrays in C and therefore the
rules for passing strings to functions are very similar to those for
passing arrays to functions. Basic rules are-
• The string to be passed must be declared as a formal argument
of the function when it is defined.
E.g. void display (char item_name[ ]){
-----
}
• The function prototype must show that the argument is a string.
void display(char str[ ]);
• A call to the function must have a string array name without
subscripts as its actual arguments.
display(names); //names is a declared string array in the calling function
Passing value Vs Pass by Pointers
• The technique used to pass data from one function to another is
known as parameter passing. It can be done in two ways-
• Pass by value (or call by value)- values of actual parameters
are copied to the variables in the parameter list of the called
function. The called function works on the copy and not on the
original values of the actual parameter. This ensures that the
original data in the calling function cannot be changed
accidentally.
• Pass by pointers (call by pointers)- The memory addresses of
the variables rather than the copies of values are sent to the
called function. In this case, the called function directly works on
the data in the calling function and the changed values are
available in the calling function for its use.
• Pass by pointer method is often used when manipulating arrays
and strings and also when we require multiple values to be
returned by the called function.
The Scope, Visibility and Lifetime of Variables
• In C, variables have a data type and storage class. Different variables
storage class are-
• Automatic variables
• External variables
• Static variables
• Register variables
• The scope of variable determines over what region of the program a
variable is actually available for use (‘active’).
• Longevity refers to the period during which a variable retains a given
value during execution of a program (‘alive’).
• The visibility refers to the accessibility of a variable from the memory.
• Variables are also broadly categorized depending on the place of
their declaration- internal (local) or external (global).
• Internal variables are those which are declared within a particular
function, while external variables are declared outside of any
function.
Automatic Variables
• Automatic variables are declared inside a function in which they are
to be utilized.
• They are created when the function is called and destroyed
automatically when the function is exited.
• They are therefore private (local) to the function in which they are
declared.
• They are also referred to as local or internal variables.
main(){ main(){
int number; auto int number;
------ ------
------ ------
} }
• A variable declared inside a function without storage class
specification is by default, an automatic variable.
• Any variable local to main will be normally alive throughout the whole
program, although it is active only in main.
Fig. 9.13 Working of automatic variables
External Variables
• Variables that are both alive and active throughout the entire program
are known as external variables or global variables.
• They can be accessed by any function in the program.
• They are declared outside a function.
int number;
float length=7.5;
main(){
----
----
}
function1( ){ function2 ( ){
---- ----
---- ----
} }
Fig. 9.14 Illustration of properties of
global variables
Global variables as parameters
• Since all function in a program source file can access global
variables, they can be used for passing values between the functions.
• Problems:
• Values of global variables which are sent to the called function
may be changed inadvertently by the called function.
• The characters of functions independency and isolation is lost If
they use global variables.
• It is not immediately apparent to the reader which values are
being sent to the called function.
• A function that uses global variables suffers from reusability.
• A global variable is available only from the point of declaration to the
end of the program.
• Global variables are initialized to zero by default.
External Declaration
main(){ main(){
y = 5; extern int y; /*external declaration*/
---- ----
} }
int y; /*global declaration*/
func1(){
func1(){ extern int y; /*external declaration*/}
y = y+1;
} int y; /*definition*/
• The external declaration of y inside the function informs the compiler that y
is an integer type defined somewhere else in the program.
• extern declaration does not allocate storage space for variables.
Static Variables
• The value of static variables persists until the end of the program.
• A variable can be declared static using the keyword static.
• static int x;
• static float y;
• A static variable may be either an internal type or an external type
depending on the place of declaration.
• Internal static variables are those which are declared inside a
function.
• The scope of internal static variables extend up to the end of the
function in which they are defined.
• internal static variables are similar to auto variables, except that
they remain in existence (alive) throughout the remainder of the
program.
• A static variable is compiled only once (i.e. when the program is
compiled.
Fig. 9.15 Illustration of static variable
Register variables
• Variables stored in machine’s registers, instead of keeping in the
memory.
• Register access is much faster than memory access.
• Example: register int count;
• Nested Blocks:
main(){
int a = 20,b = 10;
------
{
int a = 0;
int c = a + b;
-----
}
b=a;
}
Storage Where declared Visibility (Active) Lifetime (Alive)
Class
None Before all functions in a file Entire file plus other Entire program
(may be initialized) files where variable is (Global)
declared with extern
extern Before all functions in a file Entire file plus other Global
(cannot be initialized) files where variable is
extern and the file where declared
originally declared as global.
static Before all functions in a file Only in that file Global
None or Inside a function (or a block) Only in that function Until end of function
auto or block or block
register Inside a function (or a block) Only in that function Until end of function
or block or block
static Inside a function Only in that function Global
Scope Rules
• Scope: The region of a program in which a variable is available for
use.
• Visibility: The program’s ability to access a variable from the
memory.
• Lifetime: The lifetime of a variable is the duration of time in which a
variable exists in the memory during execution.
• Rules of use:
• The scope of global variable is the entire program file.
• The scope of a local variable begins at point of declaration and
ends at the end of the block or function in which it is declared.
• The scope of a formal function argument is its own function.
• The lifetime (or longevity) of an auto variable declared in main is
the entire program execution time, although its scope is only the
main function.
• The life of an auto variable declared in a function ends when the
function exited.
• A static local variable, although its scope is limited to its function,
its lifetime extends till the end of program execution.
• All variables have visibility in their scope, provided they are not
declared again.
• If a variable is redeclared within its scope again, it loses its
visibility in the scope of the redeclared variable.