You are on page 1of 16

1

Module II - Functions and Pointers


2. To understand the use of Functions and Pointers
2.1 To know Functions
2.2 To discuss passing values between Functions
2.3 To know scope rule of Functions
2.4 To know Function declaration and Prototypes
2.5 To know Pointers
2.6 To know Recursion
2.7 To understand Data Types
2.8 To list and use Storage Classes
2.9 To know features of C Preprocessor
2.10 To know Macros
2.11 To know File Inclusion

Functions
A function is a self-contained block of statements that perform a specific task of some
kind. Every C program can be thought of as a collection of these 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 order of sequence specified by the
function calls in main( ).
 After each function has done its thing, control returns to main( ).
Eg: Using Function
main( )
{
message( ) ;
printf ( "\n Using Function in our program……..”) ;
}

void message( )
{
printf ( "\ nwelcome to world of functions!!!" ) ;
}

And here’s the output...

Welcome to world of functions!!!


Using Function in our program………..

1
2

Here, main( ) itself is a function and through it we are calling the function message( ).
When we say that main( ) ‘calls’ the function message( ), it means that the control passes
to the function message( ). The activity of main( ) is temporarily suspended; it falls
asleep while the message( ) function wakes up and goes to work. When all statements in
the message( ) function completed execution, the control returns to main( ), which comes
to life again and begins executing remaining code after the function call.(at the exact
point where it was suspended).
 main( ) becomes the ‘calling’ function, whereas message( ) becomes the ‘called’
function.

Declaration, Calling and defining Functions


 Function declaration specifies what is the return type of the function and the types of
parameters it accepts.
 Function definition defines the body of the function.

 A function gets called when the function name is followed by a semicolon. For
example,
main( )
{
message( ) ; //calls the function message
}
 A function is defined when function name is followed by a pair of braces in which
one or more statements may be present. For example, message is defined as follows:
void message( )
{
printf ( "\nWelcome to functions!!" ) ;
}
 A function can be called any number of times. For example,
main( )
{
message( ) ;
message( ) ;
}
void message( )
{
printf ( "\nWelcome to functions!!" ) ;
}

 The order in which the functions are defined in a program and the order in which
they get called need not necessarily be same. For example,
main( )
{

2
3

message1( ) ;
message2( ) ;
}
void message2( )
{
printf ( "\nC Programming" ) ;
}

void Message1( )
{
printf ( "\ nWelcome to functions!!" ) ;
}
Function prototype
A function prototype is a declaration of a function that specifies the function's name and
type signature ( parameter types, and return type), but omits the function body.
Examples.
1. float square ( float ) ;
2. int add(int, int);
3. void message();

Passing Values between Functions


Argument/Parameter
− The mechanism used to convey information to the function is the ‘argument’.
− The arguments are sometimes also called ‘parameters’.
− For eg, the printf() function accepts a string/text within double quotes as its
argument. Also a function can be defined without argument as above message
function.
Actual argument: Argument present in the function call statement.
Formal argument: Argument present in the function definition.

Sending and receiving values between functions


Consider the following program.
− In this program, in main( ) we receive the values of a, b (can also done through
the keyboard) and then output the sum of a and b .
− However, the calculation of sum is done in a different function called add( ).
− If sum is to be calculated in add( ) and values of a, b are received in main( ), then
we must pass on these values to add( ), and once add( ) calculates the sum we
must return it from add( ) back to main( ).
Eg.
/* Sending and receiving values between functions */

int add( int x, int y); // function prototype. int is the type of value returned from function
main()
{
3
4

int a,b,sum;
a=10;
b=100;
sum=add(a,b) // calling function with actual arguments a and b and
assigning the value returned from function
to the variable sum.
}

//function definition
int add(int x, int y) // formal arguments x and y
{
int s;
s=x+y;
return(s); // return sum to main program
}
Note:Variables declared in a function are not available to other functions in a program

 In this program, from the function main( ) the values of a, b are passed on to the
function add( ), by making a call to the function add( ) and mentioning a, b in the
parentheses:
sum=add(a,b) ;
 In the add( ) function these values get collected in three variables x, y
add (int x, int y)

 The variables a, b are called ‘actual arguments’,whereas the variables x, y are


called ‘formal arguments’. Any number of arguments can be passed to a function
being called. However, the type, order and number of the actual and formal
arguments must always be same.
 we want to return the sum of x, y. Therefore, it is necessary to use the return
statement.

Return Statement
 The return statement serves two purposes:
(1) On executing the return statement it immediately transfers the control back to
the calling program.
(2) It returns the value present in the parentheses after return, to the calling
program. In the above program the value of sum of two numbers is being
returned.

 If we want that a called function should not return any value, in that case, we must
mention so by using the keyword void as shown below.
void message( )
{

4
5

printf ( "\nWelcome to functions!!" ) ;


}

 A function can return only one value at a time. Thus, the following statements are
invalid.
return ( a, b ) ;
return ( x, 12 ) ;

 when values are passed to a called function the values present in actual
arguments are not physically moved to the formal arguments; just a copy of
values in actual argument is made into formal arguments.(Call by value)

Call by Value and Call by Reference


 When we have passed the ‘values’ of variables to the called function, Such
function calls are called ‘calls by value’.

 So instead of passing the value of a variable, we can pass the location number
(also called address) of the variable to a function. Such function calls are called
‘calls by value’.

………………………………………………………………………………………

Eg. Different ways of using functions

1. Functions with No Arguments and No Return value


Eg. Funtion for finding the sum of two integer values

#include<stdio.h>
void add();
// function prototype written at the beginning and similar to first line of function
//definition. Keyword void indicates nothing is returned from function
main()
{
add() // calling function
}

//function definition
void add()
{
int a,b,sum;
a=10;
b=100;
sum=a+b;
printf(”the sum=%d”,sum);
5
6

return; // return statement transfers control back to main program


}
----------------------------------------------------------------------------------------------
2. Functions with Arguments and No Return value
Eg. Funtion for to find the sum of two integer values passed as arguments

#include<stdio.h>
void add( int x, int y); // function prototype
main()
{
int a,b;
a=10;
b=100;
add(a,b) // calling function with actual arguments a and b
}

//function definition
void add(int x, int y) // formal arguments x and y
{
int sum;
sum=x+y;
printf(”the sum=%d”,sum);
return; // return statement transfers control back to main program
}

Within each function call, the no of actual arguments must be same as no of formal
arguments and each actual argument must be of the same datatype of the
corresponding formal argument.
While calling the function, value of each actual argument is transferred into function
and assigned to the corresponding formal argument.
------------------------------------------------------------------------------------------------
3. Functions with Arguments and Return value
Eg. Function for to find the sum of two integer values passed as arguments and return
the result to the main program

#include<stdio.h>
int add( int x, int y); // function prototype. Int is the type of value returned from
function
main()
{
int a,b,sum;
6
7

a=10;
b=100;
sum=add(a,b) // calling function with actual arguments a and b and
assigning the value returned from function
to the variable sum.
}
//function definition
int add(int x, int y) // formal arguments x and y
{
int s;
s=x+y;
return(s); // return sum to main program
}
…………………………………………………………………………………………

Scope rule of Functions


 By default the scope of a variable is local to the function in which it is
defined.
 Variables declared in a function are not available to other functions in a program.
For eg, consider the following program

#include<stdio.h>
void funct1( int a, int b);
main()
{
int a,b;
a=10;
b=500;
printf(“before calling funct1: a=%d b=%d “, a,b);
funct1(a,b);
printf(“after calling funct1: a=%d b=%d “, a,b);
}
void funct1(int a, int b)
{
a=1; b=5;
printf(“within funct1: a=%d b=%d “, a,b);
return;
}
THE OUTPUT OF THIS PROGRAM WILL BE:
before calling funct1: a=10 b=500
within funct1: a=1 b=5
after calling funct1: a=10 b=500
7
8

Notice that a and b are unchanged in main after calling function. This illustrates that
the variables are local to the functions in which it is defined.
-------------------------------------------------------------------------------------------------------
Recursion
It is the process by which a function calls itself repeatedly until some specified
condition.
Eg. Factorial of a number
Note: factorial of 4, 4! = 4 * 3 * 2 * 1. This can be expressed as 4! = 4 * 3!
main()
{
int n,fact;
….
fact=factorial(n); //function call
}
int factorial(int x)
{
int f;
if(x==1)
f=1;
else
f=x*factorial(x-1);// call the function itself
return( f);
}
Stack is a Last in First Out data structure (LIFO) – means the last item stored on the
stack is the first item taken out from it- is used to implement recursion.
Visualisation of steps while recursive function gets called for finding 3!

8
9

Why Use Functions


The use of function provides the following advantages.
1. Writing functions avoids rewriting the same code over and over.
Suppose you have a section of code in your program that calculates area of a triangle.
If later in the program you want to calculate the area of a different triangle you are
required to write the same instructions all over again. Instead, the function allows to
write the code once and call the function many times when required.
2. If the operation of a program can be divided into separate activities, and each activity
placed in a different function, it becomes easier to write programs and easy to
modify it whenever necessary.

………………………………………………………………………………………
Pointers

Definition: Pointer is a variable which holds the address of another variable.


Within computers memory, every data item occupies one or more contiguous memory
cells.
Consider the declaration statement int v=3;
This means v is a variable that represents a an integer data item 3.

This declaration tells the C compiler to:


(a) Reserve space in memory to hold the integer value.
(b) Associate the name v with this memory location.
(c) Store the value 3 at this location.

This can be represented as


9
10

The data item can be accessed if we know the address/location of the data item. The
address of v can be determined by &v, where & is called the address operator.

Let us use another variable pv, which stores the address of v.


ie. pv=&v;
pv is called a pointer to v, since it points where v is stored in memory
Address 65522 65524(address)
65524 3
Variable pv Variable v

The data item represented by v ie the value of v ( here 3) can be accessed by the
expression *pv, where * is called indirection operator. There fore *pv and v both
represents the same item

We can print this address number through the following program:


main( )
{
int v = 3 ;
printf ( "\nAddress of v = %u", &v) ;
printf ( "\nValue of v = %d", v ) ;
}

The output of the above program would be:


Address of v = 65524
Value of v = 3

pointer operator /Indirection operator *


 Pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the
value stored at a particular address. it is declared as,
int *pv;

10
11

 This declaration tells the compiler that pv is a pointer variable ie it will be used to
store the address of an integer value.
 The address can be collected in pointer variable pv, by saying,
pv = &v ;

 Consider the following program


#include<stdio.h>
main()
{
int u=3;
int v;
int *pu, *pv // pointers to integer variables
pu=&u; // assign address of u to pu
v=*pu // assign value of u to v
pv=&v; // assign address of v to pv

printf(“u=%d &u=%d pu=%d *pu=%d”, u, &u, pu, *pu);


printf(“v=%d &v=%d pv=%d *pv=%d”, v, &v, pv, *pv)

THE OUTPUT WILL BE


u=3 &u=F8E(an address) pu=F8E *pu=3
V=3 &v=F8C pv=F8C *pv=3
………………………………………………………………………………………
Operations on pointers : Pointer Arithmetic.
An integer value can be added or subtracted from a pointer variable.
For eg, px is a pointer variable that represents address of x. we can write expressions
such as ++px,--px,(px + i),(px – i), where i is an integer

Pointers and one Dimensional arrays


 X is a one dimensional array, the address of the first element can be expressed as
either &x[0] or simply x.
 The address of the second element can be expressed as either &x[1] or simply x+1
and so on.
 General the address of the (i+1)th element can be expressed as either &x[i] or
simply x+i
since &x[i] or (x+i ) both represent the addresss of ith element, x[i] and *(x+i)
both represent the content of that address. That is the value of ith element of
array x

11
12

------------------------------------------------------------------------------------------------------

(x+1)

(x+2)

Method of accessing an individual array element x[2][3]


− ( x + 2 ) is a pointer to row 2.
− Therefore *( x + 2 ) is a pointer to first element in row 2.
− Adding 3 to this, we get *(x + 2 ) + 3, which is a pointer to 3rd column in this row
− Therefore *( *(x + 2 ) + 3 ) refers to the item in 3rd column of 2nd row.
− So x[2][3] is equivalent to *( *(x + 2 ) + 3 )
-----------------------------------------------------------------------------------------------------

The C preprocessor
 It is a program that processes our source program before it is passed to the
compiler.

 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.
 There are essentially three uses of the preprocessor--directives, constants, and
macros.
 Directives are commands that tell the preprocessor to skip part of a file, include
another file, or define a constant or macro. Directives always begin with a sharp sign
(#)
Define Constant
12
13

 Suppose a constant like 3.1415 appears many times in your program. This value
may have to be changed some day to 3.141592. Ordinarily, you would need to go
through the program and manually change each occurrence of the constant.
 However, if you have defined PI in a #define directive, you only need to make
one change, in the #define directive itself:
 #define PI 3.141592

Macros are the identifiers that represent statements or expressions. To associate


meaningful identifiers with constants, keywords, and statements or expressions, #define
directive is used.

For eg PI has defined the value 3.14 which is used to calculate area of circle.

#include<stdio.h>
#define PI 3.14
main()
{
int a,r=10;
a=PI*r*r;
printf("%d",a);
}

You can see in the given example, we have defined a macro i.e SQUARE(x) x*x. Here
the macro determines the square of the given number.

#include <stdio.h>
#include <conio.h>
#define SQUARE(x) x*x
int main()
{
int i = 2;
int j= SQUARE(i);
printf("The value of j is: %d\n", j);
getch();
return 0;
}

Macros versus Functions


 In a macro call, the preprocessor replaces the macro template with its macro
expansion, in a stupid, unthinking, literal way. As against this, in a function call the
control is passed to a function along with certain arguments, some calculations are
performed in the function and a useful value is returned back from the function.

13
14

 Usually macros make the program run faster but increase the program size,
whereas functions make the program smaller and compact. If we use a macro
hundred times in a program, the macro expansion goes into our source code at
hundred different places, thus increasing the program size. On the other hand, if a
function is used, then even if it is called from hundred different places in the
program, it would take the same amount of space in the program.

 But passing arguments to a function and getting back the returned value does take
time and would therefore slow down the program. This gets avoided with macros
since they have already been expanded and placed in the source code before
compilation.

No Macro Function

1 Macro
Function is Compiled
is Preprocessed

2 During function call,


Transfer of Control
Before Compilation takes place with
macro name is parameters.
replaced by macro Some calculations
expansion performed in the
function and a useful
value is returned back

3 make the program run Speed of Execution


faster is Slower

4 Program make the program


size Increases smaller and compact

5 Useful where small Useful where large code


code appears many appears many time
time

Use of macro can lead No side Effect


6
to side effect

7 No Type Checking Type Checking is Done

8 Generally Macros do Function can be of any


not extend beyond number of lines
one line

14
15

Macro does not Function


Check Compile Checks Compile Errors
Errors

File inclusion
The preprocessor command for file inclusion looks like this:
#include <filename>
(eg #include <math.h>)

 it simply causes the entire contents of filename to be inserted into the source code at
that point in the program.
 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.

……………………………………………………………………………………………..

Command line arguments

The arguments that we pass on to main( ) at the command prompt are called
command line arguments.
The function main( ) can have two arguments, traditionally named as argc and
argv. Out of these, argv is an array of pointers to strings and argc is an int whose value
is equal to the number of strings to which argv points. When the program is executed, the
strings on the command line are stored in memory and address of the first string is stored
in argv[0], address of the second string is stored in argv[1] and so on. The argument
argc is set to the number of strings given on the command line.

For example, consider a program which copy the contents of one file to another file.
Instead of the program prompting us to enter the source and target filenames, we must be
able to supply them at command prompt, in the form: filecopy PR1.C PR2.C
where, PR1.C is the source filename and PR2.C is the target filename.

if at the command prompt we give, filecopy PR1.C PR2.C then, argc would contain 3
argv[0] would contain base address of the string “filecopy”
15
16

argv[1] would contain base address of the string “PR1.C”


argv[2] would contain base address of the string “PR2.C”

16

You might also like