Professional Documents
Culture Documents
FUNCTIONS
FUNCTIONS
FUNCTIONS
• Defining a Function
• Accessing a function
• Function Prototypes
• Passing arguments to a function
• Recursion
• Storage classes in C
• Preprocessor
Benefits of functions
Divide and conquer
Manageable program development
Software reusability-Use existing functions as building blocks for new programs
Abstraction - hide internal details (library functions)
Avoid code repetition-The length of a source program can be reduced by using functions at appropriate places. This factor is
particularly critical with microcomputers where memory space is limited.
Debugging-It is easy to locate and isolate a faulty function for further investigations.
Functions are building blocks of C.
A function is a self-contained block of
statements that perform a coherent task of
some kind.
Every C program can be thought of as a
collection of these functions.
Function performs the same set of instructions
on different sets of data or at different portions
of a program.
Function call analogy:
Boss asks worker to complete task
Worker gets information, does task, returns
result
Functions
Every C program starts with main()function
Additional functions are called or invoked when the program
encounters function names
Functions could be
Pre-defined library functions (e.g., printf, sin, tan) or
Programmer-defined functions (e.g., my_printf, area)
Functions
Perform a specific task
May take arguments
May return a single value to the calling function
May change the value of the function arguments (call by
reference)
Functions
Any C program contains at least one function.
If a program contains only one function, it must be main( ).
If a C program contains more than one function, then one
(and only one) of these functions must be main( ), because
program execution always begins with main( ).
There is no limit on the number of functions that might be
present in a C program.
Each function in a program is called in the sequence specified
by the function calls in main( ).
C functions can be classified into two categories, namely
1. Library functions and
2. User-defined functions.
library functions are commonly required functions grouped
together and stored in a library.
This library of functions is present on the disk and is
written for us by people who write compilers for us. Almost
always a compiler comes with a library of standard
functions.
Eg: printf() and scanf() belong to the category of library
functions.
A user-defined function has to be developed by the user at the
time of writing a program to perform a specific task.
main(),area(),volume() is an example of user-defined functions.
Common Library Functions
#include <math.h> #include <stdio.h>
sin(x) // radians printf()
cos(x) // radians fprintf()
tan(x) // radians scanf()
atan(x) sscanf()
atan2(y,x) ...
exp(x) // ex
#include <string.h>
log(x) // loge x strcpy()
log10(x) // log10 x strcat()
sqrt(x) // x 0 strcmp()
pow(x, y) // xy strlen()
... ...
DEFINING AND
ACCESSING
FUNCTION
3 Elements of user-defined
functions
1.Function/Prototype Declaration
2.Function Call
3.Function Definition
Function prototype(Declaration)
Every function in C programming should be declared before they are used.
These type of declaration are also called function prototype.
Function prototype gives compiler information about function name, type of
arguments to be passed and return type.
Syntax of function prototype
return_type function_name(datatype(1) argument(1),
datatype(2) argument(2)
……….
datatype(n) argument(n));
Example:int add(int a, int b);
is a function prototype which provides following information to the
compiler:
name of the function is add()
return type of the function is int.
two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is
written before main() function.
Function call
Control of the program cannot be transferred to user-defined
function unless it is called invoked.
Syntax of function call
function_name(argument(1),argument(2),....argument(n));
return sum;
In above example, value of variable sum in add() function
is returned.
The data type of expression in return statement should
also match the return type of function.
If return type not mentioned in function declaration and
definition ,compiler assumes the function to return an
integer.
The value returned by a function can be assigned to a
variable, printed, or used in an expression
A complete Example-Functions
Void Functions
A void function may be called to
perform a particular task (clear the screen)
modify data
value
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
#include<stdio.h>
int Fibonacci(int);
void main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Storage Classes
in C
To fully define a variable one needs to mention not only its
‘type’ but also its ‘storage class’. In other words, not only do
all variables have a data type, they also have a ‘storage class’.
a variable name identifies some physical location within the
computer where the string of bits
representing the variable’s value is stored.
There are basically two kinds of locations in a computer
where such a value may be kept—
Memory and CPU registers.
It is the variable’s storage class that determines in which of
these two locations the value is stored.
a variable’s storage class tells us:
(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if
initial value is not specifically assigned.(i.e. the
default initial value).
(c) What is the scope of the variable; i.e. in which
functions the value of the variable would be available.
(d) What is the life of the variable; i.e. how long would
the variable exist.
There are four storage classes in C:
(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class
Automatic Storage Class
Storage − Memory.
Default initial value − An unpredictable value, which is
often called a garbage value.
Scope − Local to the block in which the
variable is defined.
Life − Till the control remains within
the
block in which the variable is
defined.
Following program shows how an automatic storage class variable
is declared, and the fact that if the variable is not initialized it
contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
The output of the above program could be...
1211 221
where, 1211 and 221 are garbage values of i and j. When
you run this program you may get different values
main( )
{
auto int i = 1 ;
{
{
{
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
}
The output of the above program is:
111
main( )
{
auto int i = 1 ;
{
auto int i = 2 ;
{
auto int i = 3 ;
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
The output of the above program would be:
321
Register Storage Class
The features of a variable defined to be of register
storage class are as under:
Storage - CPU registers.
Default initial value - Garbage value.
Scope - Local to the block in which
the variable is defined.
Life - Till the control remains
within the block in
which the
variable is defined.
A value stored in a CPU register can always be
accessed faster than the one that is stored in memory.
Therefore, if a variable is used at many places in a
program it is better to declare its storage class as
register. A good example of frequently used
variables is loop counters. We can name their
storage class as register.
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
Here, even though we have declared the storage class of
i as register, we cannot say for sure that the value of i
would be stored in a CPU register.
Why? Because the number of CPU registers are limited,
and they may be busy doing some other task.
What happens in such an event... the variable works as
if its storage class is auto.
Static Storage Class
The features of a variable defined to have a static storage
class are as under:
Storage − Memory.
Default initial value − Zero.
Scope − Local to the block in which
the variable is defined.
Life − Value of the variable persists
between different function
calls.
main( ) main( )
{
increment( ) ; {
increment( ) ; increment( ) ;
increment( ) ;
} increment( ) ;
increment( ) increment( ) ;
{
auto int i = 1 ; }
printf ( "%d\n", i ) ; increment( )
i=i+1;
} {
Output: 1 static int i = 1 ;
1
1 printf ( "%d\n", i ) ;
i=i+1;
}
Output : 1
2
3
External Storage Class
The features of a variable whose storage class has been
defined as external are as follows:
Storage − Memory.
Default initial value − Zero.
Scope − Global.
Life − As long as the program’s
execution doesn’t come to an end.
int i ;
main( )
{
printf ( "\ni = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
} The output would be:
increment( ) i=0
on incrementing i = 1
{ on incrementing i = 2
i=i+1; on decrementing i = 1
printf ( "\non incrementing i = %d", i ) ; on decrementing i = 0
}
decrement( )
{
i=i-1;
printf ( "\non decrementing i = %d", i ) ;
}
int x = 21 ;
main( )
{
extern int y ;
printf ( "\n%d %d", x, y ) ; Output:
} 21 31
int y = 31 ;
Here, x and y both are global variables.
int x = 10 ;
main( )
{
int x = 20 ;
printf ( "\n%d“,x);
display( ) ;
} The output would be:
display( ) 20
{ 10
printf ( "\n%d", x ) ;
}
Here x is defined at two places, once outside main( ) and once inside it.
When the control reaches the printf( ) in main( ) which x gets printed?
Whenever such a conflict arises, it’s the local variable that gets
preference over the global variable. Hence the printf( ) outputs 20.
When display( ) is called and control reaches the printf( ) there is no such
conflict. Hence this time the value of the global x, i.e. 10 gets printed.,
int x = 10 ;
void main( )
{
int x = 20 ;
{
int x = 30 ;
printf ( "\n%d", x ) ;
}
printf ("\n%d", x ) ;
}
Output:
30
20
#include <stdio.h>
void main( )
{
{ int x = 30 ;
printf ( "\n%d", x ) ;
}
printf ("\n%d", x ) ;
}
63
Preprocessor
All preprocessor directives or commands begin with a
# symbol.
E.g. #include <stdio.h>
E.g. #define MAX 100
preprocessor compiler
Directives not C statements-Do not end with ;
Dept of CSE,SKCET 64
Preprocessor Directives
File inclusion
#include
Macro definition
#define, #undef
Conditional Compilation
#if, #else, #elseif,#ifdef, #ifndef, #endif
Others
Dept of CSE,SKCET 65
File inclusion-#include Preprocessor directive
The first task of a preprocessor is file inclusion
#include directive-Puts copy of file in place of directives in
a program.
Two forms
#include <filename>
#include "filename"
directory
66 of CSE,SKCET
Dept
The #include Preprocessor Directive
Usage
Loading header files
#include <stdio.h>
Programs with multiple source files
Header file
Has common declarations and definitions
Classes, structures, enumerations, function prototypes
67 of CSE,SKCET
Dept
Standard C libraries
Build-in with your compiler
stdio.h
core input and output capabilities of C
printf() function
scanf () function
Dept of CSE,SKCET 68
Math Library Functions
Math library functions
perform common mathematical calculations
E.g. exp(), pow(), sqrt(), fabs(), sin(), cos().
#include <math.h>
Format for calling functions
FunctionName( argument, …, argument );
All math functions return data type double
Dept of CSE,SKCET 69
stdlib.h
A variety of utility functions
rand function
A function to generate a pseudo-random integer number
Return value is in the range 0 to RAND_MAX
Example:
#include <stdlib.h>
int i = rand();
• Exit()
• memory allocation
• process control
Dept of CSE,SKCET 70
string.h
All the string handling functions
strcpy
strcat
strcmp
Dept of CSE,SKCET 71
Macro definition
The second preprocessor task is expanding macro
definition.
A macro definition command associates a
name(macro name) with a sequence of
tokens(macro body).
A macro definition is of the form
#define <macro name> <macro body>
• Simplest macro is to define a constant.
E.g.
#define FALSE 0 , #define SIZE 5
Dept of CSE,SKCET 72
#define
Need to be careful in coding the macro body.
Whenever a macro call is encountered the
preprocessor replaces macro call with the macro
body.
If the macro body not created carefully it may
create an error .
E.g. #define SIZE = 10
void main()
{
int a =SIZE;// interpreted as a==10
}
Dept of CSE,SKCET 73
#define
To undefined a macro-A macro must be
undefined before being redefined to a different
value.
E.g. #undef SIZE
#define SIZE 10
void main()
{
int a [SIZE];
}
Dept of CSE,SKCET 74
Define Functions
E.g. To get the product of two variables:
#define PRODUCT(A,B) A*B
void main()
{
int x;
x = PRODUCT(3,5);
}
Preprocessing done in two steps:
1.x=A*B;
2.x = 3*5;
Dept of CSE,SKCET 75
Carefully Define Functions
#define PRODUCT(A,B) A*B
void main()
{
int x;
int a=3,b=5;
x = PRODUCT(a+1,b+1);
}
Preprocessing done in two steps:
1.x=A*B;
2.x = a+1*b+1;//but we need (a+1)*(b+1)
Solution :place parameters inside parenthesis.
#define PRODUCT(A,B) (A)*(B)
Dept of CSE,SKCET 76
Define Functions
E.g. To get the maximum of two variables:
Dept of CSE,SKCET 77
#if #else #endif expression
“If” clause statement is included in source file if given
condition is true.
Otherwise, else clause statement is included in source