Chapter3 Functions

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Chapter3_Functions 4/14/15

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()

function, there is technically no C program.


Types of C functions
There are two types of functions in C programming:


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

types of functions are known as user-defined functions. Suppose, a programmer wants to


find factorial of a number and check whether it is prime or not in same program. Then,
he/she can create two separate user-defined functions in that program: one for finding
factorial and other for checking whether it is prime or not.
How user-defined function works in C Programming?
#include <stdio.h>
void function_name()
{
................................
}
int main()
{
......................
function_name();
......................
}

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.

function prototype are not needed if user-definition function is written before


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.

Syntax of function definition


return_type function_name(type(1) argument(1),..,type(n)
argument(n))
{
//body of function
}
7
Chapter3_Functions 4/14/15

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

definition) while calling 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

definition should have same data type.


For example:


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.

Syntax of return statement


return (expression);
For example:

return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is stored in

variable sum in main() function.


The data type of expression in return statement should also match the return type of function.

10
Chapter3_Functions 4/14/15

Types of User-defined functions in C


For better understanding of arguments and return

type in functions, user-defined functions can be


categorized as:

function with no arguments and no return value

function with no arguments and return value

function with arguments but no return value

function with arguments and return value
Let's take an example to find whether a number is

prime or not using above 4 categories of user


defined functions.
11
Chapter3_Functions 4/14/15

function with no arguments and no return value.


#include <stdio.h> void prime()
void prime(); {
int main() /* There is no return value to calling function main().
{ Hence, return type of prime() is void */
prime(); //No argument is int num,i,flag=0;
passed to prime(). printf("Enter positive integer enter to check:\
return 0; n");
} scanf("%d",&num);
for(i=2;i<=num/2;++i)
{
if(num%i==0)
function prime() is used {
for asking user a input, flag=1;
check for whether }
it is prime of not and }
display it accordingly. if (flag==1)
No argument is passed printf("%d is not prime",num);
and returned from else
prime() function. printf("%d is prime",num);
}

12
Chapter3_Functions 4/14/15

function with no arguments but return value


/*C program to check whether a number entered by user is prime or not using function with no
arguments but having return value */
#include <stdio.h>
int input();
int main()
{
int num,i,flag = 0;
num=input(); /* No argument is passed to input() */
for(i=2; i<=num/2; ++i)
{
if(num%i==0) int input()
{ {
flag = 1; /* Integer value is returned from input() to
break; calling function */
} int n;
} printf("Enter positive integer to check:\n");
if(flag == 1)
printf("%d is not prime",num); scanf("%d",&n);
else
printf("%d is prime", num);
return n;
return 0; } There is no argument passed to input()
} function But, the value of n is returned
from input() to main() function.
13
Chapter3_Functions 4/14/15

function with arguments and no return value


void check_display(int n)
/*Program to check whether a number entered {
by user is prime or not using function with /* There is no return value to calling
arguments and no return value */ function. Hence, return type of
#include <stdio.h> function is void. */
void check_display(int n);
int main() int i, flag = 0;
{ for(i=2; i<=n/2; ++i)
int num; {
printf("Enter positive enter to check:\n"); if(n%i==0)
scanf("%d",&num); {
check_display(num); /* Argument num is flag = 1;
passed to function. */ break;
return 0; }
} }
Here, check_display() function is used for check if(flag == 1)
whether it is prime or not and display it printf("%d is not prime",n);
accordingly. Here, argument is passed to user- else
defined function but, value is not returned from printf("%d is prime", n);
it to calling function. }

14
Chapter3_Functions 4/14/15

function with argument and a return value


/* Program to check whether a number int check(int n)
entered by user is prime or not using function {
with argument and return value */ /* Integer value is returned from
#include <stdio.h> function check() */
int check(int n); int i;
int main() for(i=2;i<=n/2;++i)
{ {
int num,num_check=0; if(n%i==0)
printf("Enter positive enter to check:\n"); return 1;
scanf("%d",&num); }
num_check=check(num); /* Argument num is return 0;
passed to check() function. */ }
if(num_check==1) Here, check() function is used for
printf("%d is not prime",num); checking whether a number is prime
else or not. In this program, input from
printf("%d is prime",num); user is passed to function check() and
return 0; integer value is returned from it. If
} input the number is prime, 0 is
returned and if number is not prime, 1
is returned.
15
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.

Note: Positive integers are known as natural number i.e. 1, 2, 3....n


#include <stdio.h>
sum() function is invoked from the
int sum(int n); same function.
int main() For better visualization of recursion in
{ this example:
int num,add; sum(5) Every
printf("Enter a positive integer:\n"); =5+sum(4) recursive
=5+4+sum(3) function must
scanf("%d",&num); =5+4+3+sum(2) be provided
add=sum(num); =5+4+3+2+sum(1) with a way to
printf("sum=%d",add); =5+4+3+2+1+sum(0) end the
} =5+4+3+2+1+0 recursion. In
=5+4+3+2+1 this example
int sum(int n) when, n is
=5+4+3+3
{ =5+4+6 equal to 0,
if(n==0) =5+10 there is no
=15 recursive call
eturn n; and recursion
else ends.
return n+sum(n-1);/*self call to function sum()*/ 16
Chapter3_Functions 4/14/15

Storage Class[Reading assignement]


Every variable in C programming has two properties: type and storage class.

Type refers to the data type of variable whether it is character or integer or


floating-point value etc. And storage class determines how long it stays in
existence.
There are 4 types of storage class:


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

are also known as global variables.


Variables declared outside every function are external

variables.
In case of large program, containing more than one file, if

the global variable is declared in file 1 and that variable is


used in file 2 then, compiler will show error.
To solve this problem, keyword extern is used in file 2 to

indicate that, the variable specified is global variable and


declared in another file

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.

Example of register variable


register int a;
Register variables are similar to automatic variable and exists inside

that particular function only.


If the compiler encounters register variable, it tries to store variable

in microprocessor's register rather than memory.


Value stored in register are much faster than that of memory.

In case of larger program, variables that are used in loops and


function parameters are declared register variables.


Since, there are limited number of register in processor and if it

couldn't store the variable in register, it will automatically store it in


memory.
20
Chapter3_Functions 4/14/15

Storage class
Static Storage Class
The value of static variable persists until the end of the program. A variable can be

declared static using keyword: static. For example:


static int i; Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check(); Output
int main() 0 5 10
{
Check(); During first function call, it will display 0. Then, during
Check(); second function call, variable c will not be initialized to 0
Check(); again, as it is static variable. So, 5 is displayed in second
} function call and 10 in third call.
void Check()
{ If variable c had been automatic variable, the output
static int c=0; would have been:
0 0 0
printf("%d\t",c);
c+=5;
}
21
Chapter3_Functions 4/14/15

C Programming function Exercise


A program to display Prime Numbers Between two Intervals by Making

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

#include<stdio.h> In this program, user is asked to


int add(int n); enter a positive integer and sum of
int main() natural numbers up to that integer
{ is displayed by this program.
int n; Suppose, user enters 5 then,
printf("Enter an positive integer: "); Sum will be equal to 1+2+3+4+5 =
scanf("%d",&n); 15. Instead of , recursion is used in
printf("Sum = %d",add(n)); this program.
return 0;
} Output
int add(int n)
Enter an positive integer: 10
{
Sum = 210
if(n!=0)
return n+add(n-1); /* recursive call */
}

23
Chapter3_Functions 4/14/15

Exercise…
C program to Calculate Factorial of a Number Using Recursion

/* Source code to find factorial of a number. */


#include<stdio.h> This program takes a
int factorial(int n); positive integer from user
int main() and calculates the
{ factorial of that number.
int n; Instead of , this program
uses recursive function to
printf("Enter an positive integer: "); calculate the factorial of a
scanf("%d",&n); number.
printf("Factorial of %d = %ld", n, factorial(n));
Output
return 0; Enter an positive integer:
} 6
Factorial of 6 = 720
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
} 24
Chapter3_Functions 4/14/15

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

/* Example to reverse a sentence entered by user without using strings. */


#include <stdio.h>
void Reverse(); This program prints "Enter a sentence: " then,
int main() Reverse() function is called. This function stores
{ the first letter entered by user and stores in
variable c. If that variable is other than '\n'
printf("Enter a sentence: ");
[ enter character] then, again Reverse() function
Reverse(); is called.
return 0; Then, the second character is stored in variable c
} of second Reverse function. This process goes on
void Reverse() until user enters '\n'. When, user enters '\n', the
{ last function Reverse() function returns to
char c; second last Reverse() function and prints the last
scanf("%c",&c); character. Second last Reverse() function returns
if( c != '\n') to the third last Reverse() function and prints
{ second last character.
Reverse(); This process goes on and the final output will be
printf("%c“, c); the reversed sentence.
}
Output
}
Enter a sentence: margorp emosewa
awesome program
26
Chapter3_Functions 4/14/15

Exercise
C program to Calculate the Power of a Number Using Recursion

/* Source Code to calculate power using recursive function */


#include <stdio.h>
int power(int n1,int n2); Enter base number: 3
int main() Enter power
number(positive
{
integer): 3
int base, exp; 3^3 = 27
printf("Enter base number: "); This program can only
scanf("%d",&base); calculate the power if
printf("Enter power number(positive integer): "); base power and exponent
scanf("%d",&exp); are integers only. If you
printf("%d^%d = %d", base, exp, power(base, exp));need to the calculate
return 0; power of a floating point
} number then, you can
int power(int base, int exp) use .
{
if ( exp!=1 )
return (base*power(base,exp-1));
}
27
Chapter3_Functions 4/14/15

Recursion and Stack


There are different ways in which data can be organized. For example, if you are

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

well as recursive function calls.

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

on the stack is the first one to get out of it.

Now let us see how the stack works in case of the following program.

28
Chapter3_Functions 4/14/15

Recursion and Stack


 In this program before transferring the execution
#include<stdio.h> control to the add function, add( ), the values of
main( ) parameters a and b are pushed onto the stack.
Following this the address of the statement
{ printf( ) is pushed on the stack and the control is
int a = 5, b = 2, c ; transferred to add( ). It is necessary to push this
address on the stack.
c = add ( a, b ) ; In add( ) the values of a and b that were pushed on
printf ( "sum = %d", c ) ; the stack are referred as i and j.
} In add( ) the local variable sum gets pushed on the
stack.
add ( int i, int j ) When value of sum is returned sum is popped up
{ from the stack.
Next the address of the statement where the
int sum ; control should be returned is popped up from the
sum = i + j ; stack. Using this address the control returns to the
printf( ) statement in main( ).
return sum ; Before execution of printf( ) begins the two
} integers that were earlier pushed on the stack are
now popped off.

29
Chapter3_Functions 4/14/15

Recursion and Stack


How the values are being pushed and popped even though we didn’t write any code to do

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

Recursion and Stack


Note that in this program popping of sum and address is done by add( ), whereas

popping of the two integers is done by main( ).

The calling convention also decides whether the parameters being passed to the

function are pushed on the stack in left-to-right or right-to-left order.

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

The C preprocessor and its features


It is a program that processes our source program before it

is passed to the compiler.


Preprocessor commands (often known as directives) form

what can almost be considered a language within C


language.
There are several steps involved from the stage of writing a

C program to the stage of getting it executed. Figure below


shows these different steps along with the files created
during each stage.

32
Chapter3_Functions 4/14/15

preprocessor and its features


Note that if the source code is stored in a file
PR1.C then the expanded source code gets stored in
a file PR1.I.
When this expanded source code is compiled the
object code gets stored in PR1.OBJ.
When this object code is linked with the object
code of library functions the resultant executable
code gets stored in PR1.EXE.
The preprocessor offers several features called
preprocessor directives.
Each of these preprocessor directives begin with a
# symbol. The directives can be placed anywhere in
a program but are most often placed at the
beginning of a program, before the first function
definition. We would learn the following
preprocessor directives here:
(a) Macro expansion
(b) File inclusion
(c) Miscellaneous directives

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

occurrence of UPPER in the program with 25.

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

3.1415 are called their corresponding ‘macro expansions’.


When we compile the program, before the source code passes to the compiler it is examined

by the C preprocessor for any macro definitions.

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.

#define AND && #define AND &&


#define OR || #define ARANGE ( a > 25 AND a < 50 )
main( ) main( )
{ {
int f = 1, x = 4, y = 90 ; int a = 30 ;
if ( ( f < 5 ) AND ( x <= 20 OR y <= 45 ) )
printf ( "\nYour PC will always work if ( ARANGE )
fine..." ) ; printf ( "within range" ) ;
else else
printf ( "\nIn front of the maintenance printf ( "out of range" ) ;
man" ) ; }
}

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

Macros with Arguments


The macros that we have used so far are called simple macros. Macros can have

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

Macros with Arguments


Here is another example of macros with arguments:

#define ISDIGIT(y) ( y >= 48 && y <= 57 )


main( )
{
char ch ;
printf ( "Enter any digit " ) ;
scanf ( "%c", &ch ) ;
if ( ISDIGIT ( ch ) )
printf ( "\nYou entered a digit" ) ;
else
printf ( "\nIllegal input" ) ;
}

39
Chapter3_Functions 4/14/15

Macros with Arguments


Here are some important points to remember while writing macros

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

Macros with Arguments


(b) The entire macro expansion should be enclosed within parentheses. Here is an example
of what would happen if we fail to enclose the macro expansion within parentheses.
#define SQUARE(n) n * n
main( )
{
int j ;
j = 64 / SQUARE ( 4 ) ;
printf ( "j = %d", j ) ;
}
The output of the above program would be:
j = 64
whereas, what we expected was j = 4.

What went wrong? The macro was expanded into


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

command for file inclusion looks like this:


#include "filename"
and it simply causes the entire contents of filename to be inserted into
the source code at that point in the program. Of course this presumes
that the file being included is existing. When and why this feature is
used? It can be used in two cases:
(a) If we have a very large program, the code is best divided into several different
files, each containing a set of related functions. It is a good programming practice
to keep different sections of a large program separate. These files are #included at
the beginning of main program file.
(b) There are some functions and some macro definitions that we need almost in all
programs that we write. These commonly needed functions and macro definitions
can be stored in a file, and that file can be included in every program we write,
which would add all the statements in this file to our program as if we have typed
them in.
42
Chapter3_Functions 4/14/15

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

source code by inserting the preprocessing commands


#ifdef and #endif, which have the general form:
#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif
If macroname has been #defined, the block of code will be

processed as usual; otherwise not.


Where would #ifdef be useful? When would you like to

compile only a part of your program? In three cases:


45
Chapter3_Functions 4/14/15

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

Adding user defined Functions to the Library


User defined functions in C:

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

for all C programs once added to the C library.


We can use this function in any C program as we use other C library functions.

In latest version of GCC compilers, compilation time can be saved since these functions are

available in library in the compiled form.


Normal header files are saved as ”file_name.h” in which all library functions are available.

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

Adding user defined Functions to the Library


ar is an archive tool used to combine objects to create an archive file with .a

extension, also known as library.


To demonstrate the static library creation, let us create two C programs —

addition.c and multiplication.c


Using gcc, the object code for these programs are obtained, and the static library

libarith.a is created from these two objects. The steps are:


1. Create Two Sample C Programs

Create addition.c program as shown Create multiplication.c program as shown


below. below.
int addition(int a,int b) int multiplication(int a, int b)
{ {
int result; int result;
result = a + b; result = a * b;
return result; return result;
} }

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

addition.c multiplication.c addition.o multiplication.o

3. Create the C Program Static Library using ar utility


Now create the static library “libarith.a” with the addition object file and multiplication

object file as follows,


$ ar cr libarith.a addition.o multiplication.o

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 :

$ gcc -Wall example.c libarith.a -o example


#include "header.h"
int main() To Execute example executable :
{ $ ./example
int result; addition result is : 3
result = addition(1,2); multiplication result is : 6
printf("addition result is : %d\n",result);
result = multiplication(3,2);
printf("multiplication result is : %d\n",result);
}

52
Chapter3_Functions 4/14/15

Adding…..

6. Extract Object Files from an Archive Using ar


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

8. Delete a Specific Archive Member Using ar, option d


In order to delete a specific archive member from the library file, do the following.

$ ar d libarith.a addition.o
$ ar t libarith.a
multiplication.o
subtraction.o

54

You might also like