Chapter3 Functions
Chapter3 Functions
Chapter3 Functions
Chapter 3: Functions
In programming, a function is a segment that groups code to perform
a specific task.
A C program has at least one function main( ). Without main()
Library function
User defined function
Library function
Library functions are the in-built function in C programming system. For
example:
main() –
The execution of every C program starts from this main() function.
printf() –
prinf() is used for displaying output in C.
scanf() –
scanf() is used for taking input in C. 1
Chapter3_Functions 4/14/15
functions
User defined function
C allows programmer to define their own function according to their requirement. These
2
Chapter3_Functions 4/14/15
functions
As mentioned earlier, every C program begins from main() and program
starts executing the codes inside main() function. When the control of
program reaches to function_name() inside main() function. The control of
program jumps to void function_name() and executes the codes inside it.
When all the codes inside that user-defined function are executed, control
of the program jumps to the statement just after function_name() from
where it is called. Analyze the figure below for understanding the concept
of function in C programming.
3
Chapter3_Functions 4/14/15
functions
Remember, the function name is an identifier and
should be unique.
Advantages of user defined functions
User defined functions helps to decompose the large
program into small segments which makes
programmer easy to understand, maintain and
debug.
If repeated code occurs in a program. function can be
used to include those codes and execute when needed
by calling that function.
Programmer working on large project can divide the
workload by making different functions. 4
Chapter3_Functions 4/14/15
User-defined functions
Write a C program to add two integers. Make a function add to add integers and display sum in main()
function.
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main()
{
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */ }
5
Chapter3_Functions 4/14/15
User-defined functions
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(type(1) argument(1),....,type(n) argument(n));
In the above 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.
main() function.
6
Chapter3_Functions 4/14/15
User-defined functions
function call
Control of the program cannot be transferred to user-defined function unless it is
called or invoked.
Syntax of function call
function_name(argument(1),....argument(n));
In the above example, function call is made using statement
add(num1,num2); from main(). This make the control of program jump
from that statement to function definition and executes the codes inside
that function.
function definition
function definition contains programming codes to perform specific task.
User-defined functions
function definition has two major components:
1. function declarator
function declarator is the first line of function definition. When a function is
called, control of the program is transferred to function declarator.
Syntax of function declarator
return_type function_name(type(1) argument(1),....,type(n)
argument(n))
Syntax of function declaration and declarator are almost same except, there is
no semicolon at the end of declarator and function declarator is followed by
function body.
In above example, int add(int a,int b) in line 12 is a function declarator.
2. function body
function declarator is followed by body of function inside braces.
8
Chapter3_Functions 4/14/15
User-definced functions
Passing arguments to functions
In programming, argument(parameter) refers to data this is passed to function(function
In above example two variable, num1 and num2 are passed to function during function
call and these arguments are accepted by arguments a and b in function definition.
Arguments that are passed in function call and arguments that are accepted in function
If argument num1 was of int type and num2 was of float type then, argument variable a should be of type int
and b should be of type float,i.e., type of argument during function call and function definition should be same.
9
Chapter3_Functions 4/14/15
User-definced functions
Return Statement
Return statement is used for returning a value from function definition to calling function.
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is stored in
10
Chapter3_Functions 4/14/15
12
Chapter3_Functions 4/14/15
14
Chapter3_Functions 4/14/15
recursion
A function that calls itself is known as recursive function and this technique is known as
recursion in C programming.
Example: Write a C program to find sum of first n natural numbers using recursion.
automatic
external
static
register
Automatic storage class
The Keyword for automatic variable is auto. Variables declared inside the
function body are automatic by default. These variable are also known as local
variables as they are local to the function and doesn't have meaning outside that
function
Since, variable inside a function is automatic by default, keyword auto are rarely
used.
17
Chapter3_Functions 4/14/15
Storage class
External storage class
External variable can be accessed by any function. They
variables.
In case of large program, containing more than one file, if
18
Chapter3_Functions 4/14/15
Storage class
Example to demonstrate working of external variable
#include<stdio.h>
void Check();
int a=5; /* a is global variable because it is outside every function */
int main()
{
a+=4;
Check();
return 0;
}
void Check()
{
++a; /* Variable a is not declared in this function but, works in any
function */
printf("a=%d\n",a);
}
Output
a=10 19
Chapter3_Functions 4/14/15
Storage class
Register Storage Class
The Keyword to declare register variable is register.
register int a;
Register variables are similar to automatic variable and exists inside
Storage class
Static Storage Class
The value of static variable persists until the end of the program. A variable can be
User-defined function
#include<stdio.h> int check_prime(int num) /* User-defined
int check_prime(int num); function to check prime number*/
int main() {
{ int j,flag=0;
int n1,n2,i,flag; for(j=2;j<=num/2;++j)
printf("Enter two numbers(intervals): "); {
scanf("%d %d",&n1, &n2); if(num%j==0)
printf("Prime numbers between %d and {
%d are: ", n1, n2); flag=1; Output
for(i=n1+1;i<n2;++i) break; Enter two
{ } numbers(intervals): 10
flag=check_prime(i); } 30
if(flag==0) return flag; Prime numbers between
printf("%d ",i); } 10 and 30 are: 11 13 17 19
} 23 29
return 0;
}
22
Chapter3_Functions 4/14/15
Exercise…
C program to Find Sum of Natural Numbers using Recursion
23
Chapter3_Functions 4/14/15
Exercise…
C program to Calculate Factorial of a Number Using Recursion
Exercise…
/* Example to calculate GCD or HCF using recursive function. */
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d%d", &n1, &n2);
printf("H.C.F of %d and %d = %d", n1, n2, hcf(n1,n2));
return 0;
}
Output
int hcf(int n1, int n2) Enter two positive integers: 366 60
{ H.C.F of 366 and 60 = 6
if (n2!=0)
return hcf(n2, n1%n2);
else
return n1;
} 25
Chapter3_Functions 4/14/15
Exercise
C program to Reverse a Sentence Using Recursion
Exercise
C program to Calculate the Power of a Number Using Recursion
to store five numbers then we can store them in five different variables, an array, a
linked list, a binary tree, etc. All these different ways of organizing the data are
known as data structures.
The compiler uses one such data structure called stack for implementing normal as
A stack is a Last In First Out (LIFO) data structure. This means that the last item
to get stored on the stack (often called Push operation) is the first one to get out of
it (often called as Pop operation).
You can compare this to the stack of plates in a cafeteria—the last plate that goes
Now let us see how the stack works in case of the following program.
28
Chapter3_Functions 4/14/15
29
Chapter3_Functions 4/14/15
so? Simple—the compiler on encountering the function call would generate code to push
parameters and the address. Similarly, it would generate code to clear the stack when the
control returns back from add( ). Figure below shows the contents of the stack at
different stages of execution.
30
Chapter3_Functions 4/14/15
The calling convention also decides whether the parameters being passed to the
The standard calling convention always uses the right-to-left order. Thus
during the call to add( ) firstly value of b is pushed to the stack, followed by the
value of a.
The recursive calls are no different. Whenever we make a recursive call the
parameters and the return address gets pushed on the stack. The stack gets
unwound when the control returns from the called function. Thus during every
recursive function call we are working with a fresh set of parameters.
31
Chapter3_Functions 4/14/15
32
Chapter3_Functions 4/14/15
33
Chapter3_Functions 4/14/15
Macro expansion
Have a look at the following program.
#define UPPER 25
#include<stdio.h>
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form
of UPPER, which has already been defined before main( ) through the statement,
#define UPPER 25
This statement is called ‘macro definition’ or more commonly, just a ‘macro’.
What purpose does it serve? During preprocessing, the preprocessor replaces every
34
Chapter3_Functions 4/14/15
Macro expansion
Here is another example of macro definition.
#define PI 3.1415
main( )
{
float r = 6.25 ;
float area ;
area = PI * r * r ;
printf ( "\nArea of circle = %f", area ) ;
}
UPPER and PI in the above programs are often called ‘macro templates’, whereas, 25 and
When it sees the #define directive, it goes through the entire program in search of the macro
templates; wherever it finds one, it replaces the macro template with the appropriate macro
expansion.
Only after this procedure has been completed is the program handed over to the compiler.
35
Chapter3_Functions 4/14/15
Macro expansion
Following three examples show places where a #define directive is popularly
used by C programmers.
1) A #define directive is used many times to 2) A #define directive could be used even
define operators as shown below. to replace a condition, as shown below.
36
Chapter3_Functions 4/14/15
Macro expansion
3) A #define directive could be used to replace even an
entire C statement. This is shown below.
#define FOUND printf ( "The Yankee Doodle Virus" ) ;
main( )
{
char signature ;
if ( signature == 'Y' )
FOUND
else
printf ( "Safe... as yet !" ) ;
} 37
Chapter3_Functions 4/14/15
arguments, just as functions can. Here is an example that illustrates this fact.
#define AREA(x) ( 3.14 * x * x )
In this program wherever the
main( )
preprocessor finds the phrase AREA(x)
{ it expands it into the statement ( 3.14 * x
float r1 = 6.25, r2 = 2.5, a ; * x ).
However, that’s not all that it does.
a = AREA ( r1 ) ;
The x in the macro template AREA(x)
printf ( "\nArea of circle = %f", a ) ; is an argument that matches the x in the
a = AREA ( r2 ) ; macro expansion ( 3.14 * x * x ).
printf ( "\nArea of circle = %f", a ) ;
} The statement AREA(r1) in the
Here’s the output of the program...
program causes the variable r1 to be
substituted for x. Thus the statement
Area of circle = 122.656250 AREA(r1) is equivalent to:
Area of circle = 19.625000 ( 3.14 * r1 * r1 )
38
Chapter3_Functions 4/14/15
39
Chapter3_Functions 4/14/15
with arguments:
(a) Be careful not to leave a blank between the macro template and
its argument while defining the macro. For example, there should be
no blank between AREA and (x) in the definition, #define
AREA(x) ( 3.14 * x * x ).
If we were to write AREA (x) instead of AREA(x), the (x) would
become a part of macro expansion, which we certainly don’t want.
What would happen is, the template would be expanded to
( r1 ) ( 3.14 * r1 * r1 )
which won’t run. Not at all what we wanted.
40
Chapter3_Functions 4/14/15
j = 64 / 4 * 4 ;
which yielded 64.
41
Chapter3_Functions 4/14/15
File Inclusion
This directive causes one file to be included in another. The preprocessor
File Inclusion
It is common for the files that are to be included to have a .h extension.
This extension stands for ‘header file’, possibly because it contains statements which when
included go to the head of your program. The prototypes of all the library functions are
grouped into different categories and then stored in different header files. For example
prototypes of all mathematics related functions are stored in the header file ‘math.h’,
prototypes of console input/ output functions are stored in the header file ‘conio.h’, and so
on.
Actually there exist two ways to write #include statement. These are:
#include "filename"
#include <filename>
The meaning of each of these forms is given below:
#include "goto.c"
This command would look for the file goto.c in the current directory as well as the
specified list of directories as mentioned in the include search path that might have
been set up.
#include <goto.c>
This command would look for the file goto.c in the specified list of directories only.
43
Chapter3_Functions 4/14/15
example
First create a file of file name cube.h which Now create any another c file let
contains: example.c which contains:
int cube ( int a) #include “cube.h”
{ #include<stdio.h>
int b; void main()
b=(a)*(a)*(a); {
return b; int p=5,q;
} q=cube(p);
printf(“%d”,q);
}
Output: 125
Explanation:
When we write #include “cube.h” the compiler includes contents of file cube.h i.e.
cube function in the example.c file. So we can use the function which has defined in
cube.h .
44
Chapter3_Functions 4/14/15
Conditional Compilation
We can, if we want, have the compiler skip over part of a
Miscellaneous Directives :
#pragma Directive :
This directive is a special-purpose directive that you can
use to turn on or off certain features.
Pragmas vary from one compiler to another.
There are certain pragmas available with Microsoft C
compiler that deal with formatting source listings and
placing comments in the object file generated by the
compiler.
Turbo C/C++ compiler has got a pragma that allows you
to suppress warnings generated by the compiler.
Some of these pragmas are discussed below.
46
Chapter3_Functions 4/14/15
#pragma Directive
#pragma startup and #pragma exit: These directives allow us to specify functions that
a)
are called upon program startup (before main( )) or program exit (just before the program
terminates). Their usage is as follows:
void add1( ) ;
void add2( ) ; And here is the output of the program.
#pragma startup add1 Inside add1
#pragma exit add2 Inside main
main( ) Inside add2
{
printf ( "\nInside main" ) ; Note that the functions add1( ) and add2( )
} should neither receive nor return any value.
void add1( )
If we want two functions to get executed at
{ startup then their pragmas should be defined in
printf ( "\nInside add1" ) ; the reverse order in which you want to get them
} called.
void add2( )
{
printf ( "\nInside add2" ) ;
}
47
Chapter3_Functions 4/14/15
#pragma Directive
(b) #pragma warn: This directive tells the compiler whether or not we want to suppress a specific
warning. Usage of this pragma is shown below.
#pragma warn –rvl /* return value */ If you go through the program you can notice three
#pragma warn –par/* parameter not used */ problems immediately. These are:
#pragma warn –rch /* unreachable code */ (a) Though promised, f1( ) doesn’t return a value.
int f1( ) (b) The parameter x that is passed to f2( ) is not being used
anywhere in f2( ).
{ (c) The control can never reach x++ in f3( ).
int a = 5 ; If we compile the program we should expect warnings
} Void main() indicating the above problems.
void f2 ( int x ) { However, this does not happen since we have suppressed the
f1( ) ; warnings using the #pragma directives.
{ If we replace the ‘–’ sign with a ‘+’ then these warnings
printf ( "\nInside f2" ) ; f2 ( 7 ) ; would be flashed on compilation.
f3( ) ; Though it is a bad practice to suppress warnings, at times it
} } becomes useful to suppress them.
int f3( ) For example, if you have written a huge program and are
trying to compile it, then to begin with you are more interested
{ in locating the errors, rather than the warnings. At such times
int x = 6 ; you may suppress the warnings. Once you have located all
return x ; errors, then you may turn on the warnings and sort them out.
x++ ;
}
48
Chapter3_Functions 4/14/15
As you know, there are 2 types of functions in C. They are, library functions and user
defined functions.
Library functions are inbuilt functions which are available in common place called C
library. Where as, User defined functions are the functions which are written by us for our
own requirement.
Do you know that we can add our own user defined functions in C library?
Yes. It is possible to add, delete, modify and access our own user defined function to or
from C library.
The advantage of adding user defined function in C library is, this function will be available
In latest version of GCC compilers, compilation time can be saved since these functions are
These header files contain source code and this source code is added in main C program file
where we add this header file using “#include <file_name.h>” command.
49
Chapter3_Functions 4/14/15
50
Chapter3_Functions 4/14/15
Adding…….
2. Compile the Programs and Get Object Codes
Use -c option to compile both the c program. Using option -c will create the
corresponding .o files.
$ gcc -c addition.c
$ gcc -c multiplication.c
Now, the current working directory contains both the .c and .o files as shown below.
$ ls
51
Chapter3_Functions 4/14/15
Adding….
4. Write C program to Use the Library libarith.a
The library file libarith.a is now ready to usage. Following example indicates how to write a
sample C program with the header file to use the libarith.a static library.
Create header.h :
#include <stdio.h>
int addition(int a,int b);
5. Compilation
int multiplication(int a,int b); To Compile example.c :
Create example.c :
52
Chapter3_Functions 4/14/15
Adding…..
Command, option x
You can extract the object files available in an
archive as follows.
$ mkdir object
$ cp libarith.a object/
$ cd object
$ ar x libarith.a
$ ls * .o
addition.o
multiplication.o
53
Chapter3_Functions 4/14/15
Adding…..
7. Add an Object File into the Existing Archive Using ar, option r
Let assume that you have create another object file called subtraction.o
The following command extends the libarith.a library file, by inserting subtraction.o object
as shown below.
$ ar r libarith.a subtraction.o
$ ar t libarith.a
addition.o
multiplication.o
subtraction.o
$ ar d libarith.a addition.o
$ ar t libarith.a
multiplication.o
subtraction.o
54