Anda di halaman 1dari 17

# Unit IV

## Function and Pointers

Syllabus
Function Definition of Function Declaration of Function
Pass by Value Pass by Reference Recursion Pointers
Definition Initialization Pointers Arithmetic Pointers and Array
Example Problems.

Chapter 4

## 5.1. Functions User Defined Functions

Real Time Examples
We have got various functions in our body for doing specific tasks.
Heart for pumping blood in veins
Lungs for breathing
Eyes for vision
Legs for walking
Nose for smell
Solutions
Similarly in programming we need something to handle our repetitive or specific task that is called function.
A function
i) accepts some input
ii) processes it
iii) produces output.
Function Concept in Mathematics
f(x) = 5x 3
where
f is a function name
x is an argument or input of a function
5x-3 is a definition of a function.
When x = 1,
f(1) = 5(1) 3
f(1) = 2
2 is the return value of the function.
When x=2,
f(2) = 5(2) 3
f(2) = 7
7 is the return value of the function.
So, every function must have name, argument (input) and return (output) type.

## Consider another example,

sum(x,y) = x + y.
where
sum is a function name
x,y is an argument or input of function
x+y is a definition of a function.
When x = 2, y = 3,
sum(2,3) = 2+3 = 5
Here 2,3 are arguments and 5 is the return value.

## 5.1.1. Introduction to Functions

Functions are a block of statements (called modules) that perform a specific task assigned by the user.Functions
accept an input, perform a task and produce the output.

Input

Function

Output

Function reduces the redundancy of code.It breaks down a large program into small modules to improve readability and portability as well as to make the program easy to debug.
Functions can be categorized into two types:
1. Pre-Defined function
2. User Defined function
Pre-Defined vs User Defined
Pre-Defined Function

## User defined functions are the function which are created

by users as per their ownrequirements.

## Pre-defined functions are part of header file(such as

math.h) which is called runtime.

## User defined functions are part of the program which is

called during compiling.

changed.

## The declaration and definition of afunction is already

known to the compiler.

program.

## 5.1.2. Need for Functions

If we want to execute a block of statements again and again repeatedly, then we have to repeat the block of
statements again and again, which will increase the size of program code, but if we place the block of statements that will be repeated inside the function, then we need not repeat the block of code again and again,
instead we can just call the function again and again.

## Consider the following example:

2,3

3,4

4,5

5,6

11

6,7

13

In the above illustration only the input and output arechanging, but the function add remains constant.
So we need not write add the function again and again, instead we can write the add function only once and
call it again with different sets of inputs.
2,3

3,4

4,5

5,6

11

6,7

13

## 5.1.3. Advantages of Writing Function

1. Modular and Structural Programming
We can divide c program into smaller modules.
For example:A calculator program can be divide into four modules such as add,subtract,multiply
and divide.
We can call these modules whenever required.
Modules once created can be re-used in other programs.
2. Individual functions can be built independently without any ambiguity.
3. More than one module can be developed parallelly.
4. Testing can be done effectively when we test individual modules rather than testing the entire program.
5. Frequently used functions can be put together in the customized library.
Frequently used functions can be put in our custom header file and it can be included in other
programstoo.

## 6. A function can call other functions andalso itself.

Function can call other function.
Function can call itself, which is called recursive function.
Recursive functions are also useful in order to write system functions.
7. It is easier to understand the program when a program is divided into small modules.
We can get overall idea of the program by just looking at the function names.

## 5.1.4. Elements of a User Defined Function

5.1.4.1. Function Name
A function name is any variable name that the user gives to the function.
Function naming rule

## Name of function includes only alphabets, digit and underscore.

First character of name of function must be an alphabet or underscore.
Name of function cannot be any keyword of c program.
Name of function cannot be a global identifier(global variable name).
Two functions cannot have same name within the scope.
Name of function is case sensitive(abc and Abc are two different functions).

5.1.4.2. Arguments/Parameter
Arguments are nothing but the input that has been given to the function.The parameters can be passed to a
function by two different methods.
a) Pass by value: In this approach only the copy of the actual variables is passed as aninput to the function.
Hence any modification done inside the function will not be reflected in the actual variable.
b) Pass by reference: In this approach the memory address of the actual variables is passed as a parameter to the function. Hence any modification done inside the function will be reflected in the actual
variable.
Note: Argument should have a valid data type.
Parameter: The names given in the function definition are called parameters.
Argument: The values supplied in the function call are called arguments.
5.1.4.3. Return Type
The return type is nothing but the output or result obtainedafter the execution of the functions.
Using return keyword output can be passed from the function.
When the program control reaches the return keyword it immediately terminates the execution of that
function and transfers the control to the calling function.
Note: A function can return only one value. Return type should be a valid data type.

## 5.1.5. Various Blocks of a Function

Any function needs to have the following three blocks.
1. Function Declaration introducing the function to the compiler
2. Function Definitiondefining the role of the function
3. Function Callingcalling the function
5.1.5.1. Function Declaration
Declaration of function in C is called Prototype Declaration.
Function declaration is also called Function Prototype.

## 6 Functions and Pointers

Function declaration is similar to a variable declaration. It provides the following information to the compiler.
It should contain three parts.
1. The return type(the data type of the result/output)
2. The function name
3. The parameter list(the data type of the inputs)
Some important points in function declaration:
Prototype declaration should always end with a semicolon.
Parameter list is optional.
Default return type is integer.
Note: if there are no parameters or return type in a function, you can specify as void.
Syntax
Return Type Function Name(Argument Type1, Argument Type2, ...., Argument TypeN);

Example
If you are going to create a function name add, that accepts two integer values as input, adds the two
values and gives the result as integer value, then the function declaration would be as follows:
Few more examples of function declaration are given below:
Function with no argument and integer as return type
int getValue(void);
Function with integer argument and integer as return type
int square(int);
Function with no argument and no return type
void display(void);
Note:
If function definition is written after the main function, then we need only Prototype Declaration in Global
Declaration Section.
If function definition is written before the main function, then we dont need write Prototype Declaration.
Functions declaration doesnt reserve any memory space.
Example Program
Function Definition Written After Main
#include<stdio.h>
void show();// Function Declaration
void main()
{
displayMessage();
}
void show()
{
printf(After Main);
}

## Function Definition Written Before Main

#include <stdio.h>
void show()
{
printf(Before Main);
}
void main()
{
displayMessage();
}
Here the function definition is written above the main function so there is no Function Declaration.

## More on Function Declaration

If we write function declaration
1. The prototype declaration tells compiler that we are going to define this function somewhere in the program.
2. Compiler will have prior information about function.
3. As the compiler have prior information, during function calling compiler looks forward in the program for
the function definition.
If we dont write function declaration, then
1. Compiler doesnt have any reference of function.
2. Compiler doesnt have prior information of that function.
3. Compiler gets confused and throws error.
5.1.5.2. Function Definition
It defines what specific task a function should do. This is done by including the block of the statement (that
does a specific task) inside the function.

## Function definition is nothing but body of the function.

It contains Executable Code(executable statements).
It defines what task a function should do.
First line of is called Function Header.
Function Header should beidentical to function Prototype but
There is no semicolon at the end.
It specifies the variable name of the input data type too.

Return Type
Function Name
Local Declaration

## int sum (int a, int b)

{
int c;

Parameter List
(Formal Parameters)

c = a + b;
return (c);
}
Statements

Return Statement

## 8 Functions and Pointers

Syntax
ReturnType FunctionName(ArgumenTtype with VariableName)
{
Block of statements;
}
Block of statements may include variable declarations, statements and return value.
Note: The return statement forces the function to return immediately eventhough if function is not yet completed.
Example of function definition
{
int c;
c = a+b;
return c;
}
Note: In the argument list of function definition, you specify the variable name also.A semicolon should not be placed at
the end of the first line of the function definition.
Another Example
{
int c;
return c;
c=a+b;
}
Here the function terminates after reaching the return statement without executing the statement return c.
Example Program
#include<stdio.h>
int add(int a,int b) //Function Definition
{
return a+b;
}
void main()
{
int x=10,y=20;
int sum;
printf(\nSum =%d,sum);
}
Output
30

## 5.2.8. Pointer and Array

An array and pointer go hand in hand with each other. An array can be accessed by using pointer. Arrays
and pointers are synonymous in terms of how they use to access memory. But the important difference
between them is that a pointer variable can take different addresses as value, whereas in case of array it is
fixed.
Relation between Arrays and Pointers
Array elements are stored in consecutive memory location.

Example 1
Consider and array:
int arr;
arr
arr arr arr arr

## Figure: Array as Pointer

In arrays of C programming, name of the array always points to the first element of an array. Here, address of
first element of an array is &arr.arr represents the address of the pointer where it is pointing. Hence, &arr
is equivalent to arr.
The statement
int arr={10};
is
equivalent to

int *arr;
arr=10;
arr = &a;
Similarly,
&a is equivalent to (a+1)AND, a is equivalent to *(a+1).

## &a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).

In C, you can declare an array and can use pointer to access the elements of an array

## 10 Functions and Pointers

Program
//Program to find the sum of six numbers with arrays and pointers.
#include<stdio.h>
void main()
{
int i,class,sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i));// (class+i) is equivalent to &class[i]
sum +=*(class+i);// *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum = 21

Example 2
int a={10,20,30,40,50};
Variable

a

a

a

a

a

Value

10

20

30

40

50

1010

1012

1014

1016

1018

Here a is the starting element and the address of a is called the base address
Value of a = 10.
Value of a = 20.
Value of a = 30.
Value of a = 40.
Value of a = 50.
Then Value of a =?
Now what will the variable a hold and what will happen when the value of a is printed?
Consider the statement below:
printf(%d,a);
The output of the statement would be 1010 since an array variable will hold the base address;
Now when we declare a variable as
int a;

## Functions and Pointers 11

something equivalent to the following will happen within the compiler implicitly(i.e. the statements will not be
visible but will happen within the compiler )
int *a;// an array variable will be considered as pointer
a = &a;// the base address of an array will be stored in the variable a.
Then value of a =&a(address of first array variable).
Let us see how the elements of the array are accessed using pointer. As we know the array variable a is also
considered as pointer and it will hold the variable a.
If we increment the array variable a, then it will move to the next element.
a=>contains the address of the first element.
*a=>contains the value of the first element.
It means a = 10.
a+1=> contains the address of the second element
*(a+1) =>contains the value of the second element.
It means a+1 = a = 20.
a+2=> contains the address of the third element
*(a+2) =>contains the value of the third element
It means a+2 = a = 30.
a+3=> contains the address of the fourth element
*(a+3) =>contains the value of the fourth element
It means a+3 = a = 40.
a+4=> contains the address of the fifth element.
*(a+4) =>contains the value of the fifth element
It means a+4 = a = 50.
Using dereferencing pointer, we can access the value of elements as follows.
*a or a

10

*(a+1) or a

20

*(a+2) or a

30

*(a+3) or a

40

*(a+4) or a

50

## 5.2.9. Pointer to Functions (Function Pointer)

A pointer which keeps address of a function is known as Function Pointer.
No function can return more than one value. But using pointers we can return more than one value.
Consider the example below;let us try to return two values at a time.
void main()
{
int a=10,b=5;
a,b=square(a,b);//this is meaningless and not supported by c
printf(%d %d,a,b);
}

## void square(int j,int k)

{
j=j*j;
k=k*k;
return(j,k);//Error: a function cannot return two values at a time.
}
Variable
Value

(Actual Parameter)

(Formal Parameter)

10

100

25

1010

1012

1014

1016

The above example illustrates that it is not possible to return two values and without returning the values, the
updated values will not be reflected in the main function.
So using pointer, we pass the address of the value and in the called function when the value is updated, it will
be directly updating in the memory location and so it will be reflected in the main function.

Example 1
#include <stdio.h>
void main()
{
int a=10,b=5;
printf(%d %d,a,b);
}
void square(int *j,int *k)
{
*j=(*j)*(*j); // updation is done directly in the memory location of variablea.
*b=(*b)*(*b); // updation is done directly in the memory location of variableb.
}
Variable
Value

(actual parameter)

(ptr variable)

*j

*k

10

100

25

1010

1012

1010

1012

Explanation:
&a and j refer to same memory location and hence any updates done using the pointer variable j will affect the
value of a.
&b and k refer to same memory location and hence any updates done using the pointer variable k will affect
the value of b.
Output
100 25

## 5.2.10. Pointer to Structure

A pointer which is pointing to a structure is known as Pointer to Structure.
Structures member can be accessed through pointer.
Consider an example to access structures member through pointer.

Example 1
Using dot(.) operator:
#include <stdio.h>
struct book
{
int pages;
float price;
};
void main()
{
struct book *ptr;
struct book p;
ptr=&p;/* Referencing pointer to memory address of p */
printf(Enter no of pages: );
scanf(%d,&(*ptr).pages); // (*ptr).pages is equivalent to p.pages
printf(Enter price: );
scanf(%f,&(*ptr).price); // (*ptr).price is equivalent to p.price
printf(/nDisplaying:/n );
printf(%d%f,(*ptr).pages,(*ptr).price);
}
Output:
Enter no of pages:450
Enter price: 220.75
Displaying:
450 220.75

In this example, the pointer variable of type struct is referenced to the address of p. Then the structure member
is accessed through pointer using dot operator.
Structure pointer member can also be accessed using -> operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b
-> and(*).Bothrepresent the same but operator will not have * in front.
These operators are also used to access data member of structure by using structures pointer.

## 14 Functions and Pointers

Example 2
#include <stdio.h>
struct book
{
int pages;
float price;
};
void main()
{
struct book *ptr;
struct book p;
ptr=&p;/* Referencing pointer to memory address of p */
printf(Enter no of pages: );
scanf(%d,&ptr->pages); // (*ptr).pages is equivalent to p.pages
printf(Enter price: );
scanf(%f,&ptr->price); // (*ptr).price is equivalent to p.price
printf(/nDisplaying:/n );
printf(%d %f,ptr->pages,*ptr->price);
}
Output:
Enter no of pages:450
Enter price: 220.75
Displaying:
450 220.75

## 5.2.11. Void Pointer

void pointer is a pointer that can store the address of any type of variable.
Introduction
Suppose if we have to declare integer pointer, character pointer and float pointer, then we need to declare
three pointer variables.
Instead of declaring different types of pointer variable, it is possible to declare single pointer variable which
can act as integer pointer, character pointer or floating point pointer.
This general purpose pointer variable is called void pointer.
It does not have any data type associated with it.
It can store address of any type of variable.
Declaration of void pointer
Syntax
void * pointerVaraibleName;

## Functions and Pointers 15

Example
void *ptr;
Consider the below example to clearly understand the void pointer:
void *ptr;// ptr is declared as Void pointer
char cnum;
int inum;
float fnum;
ptr = &cnum;// ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum;// ptr has address of float data
Explanation
We have declared three variables of integer,character and float type.

When we assign address of integer to the void pointer, pointer will become Integer Pointer.
When we assign address of Character Data type to void pointer it will become Character Pointer.
When we assign address of floating point Data type to void pointer it will become floating point Pointer
It is capable of storing address of any data type

## 5.2.12. Null Pointer

A pointer which does not point to any memory location is called NULL Pointer.
Meaning of NULL
NULL is macro constant which has been defined in the header file stdio.h, alloc.h, mem.h, stddef.h and
stdlib.h as #define NULL 0
Example
int *a;
int *b = NULL;
here *a and *b are not same because b points to NULL and a may point to some garbage address
(a == b)

(a == NULL )

## FALSE, in most case

(b == NULL )

ALWAYS true

Example program:
Void main()
{
int *a;
int *b =NULL;
printf(value of a =%d \t value of b =%d,a,b);
}
Output:
Value of a = 28620 value of b = 0
NULL is a reserved word in most high-level languages. It is an EXPLICIT value, and not anundefinedvalue.

## 5.2.13. Wild Pointer

A pointer in c which has not been initialized is known as wild pointer.
Example
What will be output of following c program?
#include<stdio.h>
void main()
{
int *p;
printf(%u\n,p);
}
Output
28618

## Here the output is just any random address (Garbage value)

Here p is wild pointer because it has not been initialized. Wild pointer doesnt point any specific memory
location.

## 5.2.14. Dangling Pointer

If a pointer is pointing to the memory address of a variable and after sometimes, if the variable has been deleted
from that memory location, then the pointer will still be pointing to the same memory location. Such pointer is
known as dangling pointer and this problem is known as dangling pointer problem.
Initially:
ptr

5000

25

8000

5000

ptr

5000

25

8000

5000

Later:

## 5.2.15. Far vs Near

The pointer which can point or access whole of the residence memory of RAM, i.e. which can access all 16 segments, is known as far pointer. The size of far pointer is 4 bytes.
The pointer which can point or access only 64KB data segment of RAM, i.e. which can access only 8 segments,
is known as far pointer. The size of far pointer is 4 bytes.
Difference between void pointer, NULL pointer, wild pointer and dangling pointer.

void pointer

NULL pointer

wild pointer

dangling pointer