Unit 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

303105104 - Computational Thinking for

Structured Design-1
Dr. Chintan B. Thacker, Assistant Professor, Computer Science & Engineering
CHAPTER-4
Functions , Pointer Functions, Recursion , Storage classes:
Contents

1. Functions
2. Pointer Functions
3. Recursion
4. Storage classes
1. Function :

● A function in C is a set of statements that when called perform


some specific task.
● It is the basic building block of a C program that provides modularity
and code reusability. The programming statements of a function are
enclosed within { } braces, having certain meanings and performing
certain operations.
● They are also called subroutines or procedures in other languages.
Syntax of Functions in C

The syntax of function can be divided into 3 aspects:


Function Declaration
Function Definition
Function Calls
Function Declarations
● In a function declaration, we must
provide the function name, its return
type, and the number and type of its
parameters.
● A function declaration tells the
compiler that there is a function with
the given name defined somewhere
else in the program.
● Syntax:
● return_type name_of_the_function
(parameter_1, parameter_2);
Function Definition
The function definition consists of actual statements
which are executed when the function is called (i.e. when
the program control comes to the function).
return_type function_name
A C function is generally defined and declared in a (para1_type para1_name, para2_type
single step because the function definition always para2_name)
starts with the function declaration so we do not {
need to declare it explicitly. The below example // body of the function
serves as both a function definition and a }
declaration.
Structure :
Function Call:
• A function call is a statement that instructs the compiler to execute
the function. We use the function name and parameters in the
function call.

• In the below example, the first sum function is called and 10,30 are
passed to the sum function. After the function call sum of a and b
is returned and control is also returned back to the main function
of the program.
Working concept :

Note: Function call is necessary to bring


the program control to the function
definition. If not called, the function
statements will not be executed.

• In the given example, the first sum function is called


and 10,30 are passed to the sum function. After the
function call sum of a and b is returned and control
is also returned back to the main function of the
program.
Example:
: // C program to show function // Driver code
// call and definition int main()
#include <stdio.h> {
// Calling sum function and
// storing its value in add variable
// Function that takes two parameters int add = sum(10, 30);
// a and b as inputs and returns
// their sum printf("Sum is: %d", add);
return 0;
int sum(int a, int b) }
{
return a + b;
}
● Output
● Sum is: 40
● As we noticed, we have not used explicit function declaration.
We simply defined and called the function.
Function Return Type

• Function return type tells what type of value is returned after all function is executed.
• When we don’t want to return a value, we can use the void data type.

Example:

int func(parameter_1,parameter_2);

The above function will return an integer value after running statements inside the function.

Note: Only one value can be returned from a C function. To return multiple values, we have to use pointers or
structures.
Function Arguments:
• Function Arguments (also known as Function Parameters) are the data that is passed to a function.

Example:

int function_name(int var1, int var2);

Conditions of Return Types and Arguments


• In C programming language, functions can be called either with or without arguments and might return values.
• They may or might not return values to the calling functions.
1) Function with no arguments and no return value
2) Function with no arguments and with return value
3) Function with argument and with no return value
4) Function with arguments and with return value
Function Arguments:
1) Function with no arguments and no return value
Function Arguments:
2) Function with no arguments and with return value
Function Arguments:
3) Function with argument and with no return value
Function Arguments:
4) Function with arguments and with return value
How Does C Function Work?
Working of the C function can be broken into the following steps as mentioned below:
Declaring a function: Declaring a function is a step where we declare a function. Here we define
the return types and parameters of the function.
Defining a function:
Calling the function: Calling the function is a step where we call the function by passing the
arguments in the function.
Executing the function: Executing the function is a step where we can run all the statements
inside the function to get the final result.
Returning a value: Returning a value is the step where the calculated value after the execution of
the function is returned. Exiting the function is the final step where all the allocated memory to
the variables, functions, etc is destroyed before giving full control to the main function.
Types of Functions
There are two types of functions in C:
• Library Functions
• User Defined Functions
1. Library Function
Flowchart of For Loop
A library function is also referred to as a “built-in function”. A compiler package
already exists that contains these functions, each of which has a specific meaning
and is included in the package. Built-in functions have the advantage of being
directly usable without being defined, whereas user-defined functions must be
declared and defined before being used.

For Example:

pow(), sqrt(), strcmp(), strcpy() etc.


Example: for loop

Advantages of C library functions


C Library functions are easy to use and optimized for better performance.
C library functions save a lot of time i.e, function development time.
C library functions are convenient as they always work.
Library Function
// C program to implement
// the above approach printf("The Square root of %.2lf = %.2lf",
#include <math.h> Number, squareRoot);
#include <stdio.h> return 0;
}
// Driver code
int main()
{
double Number; Output
Number = 49; The Square root of 49.00 = 7.00
// Computing the square root with
// the help of predefined C
// library function
double squareRoot = sqrt(Number);
2. User Defined Function

• Functions that the programmer creates are known as User-Defined functions or “tailor-made functions”.
User-defined functions can be improved and modified according to the need of the programmer.
• Whenever we write a function that is case-specific and is not defined in any header file, we need to
declare and define our own functions according to the syntax.

Advantages of User-Defined Functions

• Changeable functions can be modified as per need.


• The Code of these functions is reusable in other programs.
• These functions are easy to understand, debug and maintain.
User Defined Function Example:
// C program to show
// user-defined functions
#include <stdio.h> Output
Sum is: 70
int sum(int a, int b)
{
return a + b;
}

// Driver code
int main()
{
int a = 30, b = 40;

// function call
int res = sum(a, b);

printf("Sum is: %d", res);


return 0;
}
Passing Parameters to Functions

• The data passed when the function is being invoked is known as the Actual parameters.
• In the below program, 10 and 30 are known as actual parameters.
• Formal Parameters are the variable and the data type as mentioned in the function
declaration.
• In the below program, a and b are known as formal parameters.
Example:
We can pass arguments to the C function in two ways:
Call by Value
call by Reference
1. Call by Value:
Parameter passing in this method copies values from actual parameters into
formal function parameters. As a result, any changes made inside the
functions do not reflect in the caller’s parameters.
call by Value example :

// C program to show use int var1 = 3, var2 = 2;
// of call by value printf("Before swap Value of var1 and var2 is:
#include <stdio.h> %d, %d\n",
var1, var2);
void swap(int var1, int var2)
{ swap(var1, var2);
int temp = var1; printf("After swap Value of var1 and var2 is:
var1 = var2; %d, %d",
var2 = temp; var1, var2);
} return 0;
}
// Driver code
int main()
Before swap Value of var1 and var2 is: 3,
{
2
After swap Value of var1 and var2 is: 3, 2
2. Call by Reference
► The caller’s actual parameters and the function’s actual parameters refer to
the same locations, so any changes made inside the function are reflected in
the caller’s actual parameters.

We will discuss with this by an example :


Example :

// C program to show use of int var1 = 3, var2 = 2;


// call by Reference printf("Before swap Value of var1 and
#include <stdio.h> var2 is: %d, %d\n",
void swap(int *var1, int *var2) var1, var2);
► swap(&var1, &var2);
{
int temp = *var1; printf("After swap Value of var1 and var2
*var1 = *var2; is: %d, %d",
*var2 = temp; var1, var2);
► return 0;
}
// Driver code }
int main()
{
Output :
Output
Before swap Value of var1 and var2 is:
3, 2
After swap Value of var1 and var2 is: 2,
3
Advantages of Functions in C

Functions in C is a highly useful feature of C with many advantages as mentioned


below:

• The function can reduce the repetition of the same statements in the program.

• The function makes code readable by providing modularity to our program.

• There is no fixed number of calling functions it can be called as many times as you
want.
• The function reduces the size of the program.

Once the function is declared you can just use it without thinking about the internal
working of the function.
Disadvantages of Functions in C

The following are the major disadvantages of functions in C:

• Cannot return multiple values.


• Memory and time overhead due to stack frame allocation and transfer
of program control.
Function Pointer in C
• In C language variables, instructions of a function are also stored in a memory and have an address
• A pointer pointing to the address of a function is called Function Pointer
• A Function Pointer in C can be used to create function calls to the function they point to just like a normal
function
Function Pointer in C
#include <stdio.h>

void test() {
Address of variable = 0x7ffd7f36a224
// test function that does nothing
Address of a function = 0x55f8e8abb169
return ;
}

int main() {
int a = 5;
// printing the address of variable a
printf("Address of variable = %p\n", &a);
From this example we can observe that just like a variable has
// printing the address of function main()
an address in memory, our function test() also has an address
printf("Address of a function = %p", test);
return 0;
}
Function Pointer in C
• For example, in the above figure we have a function add() to add two
integer numbers. Here, the function name points to the address of the
function itself so we are using a function pointer fptr that stores the
address of beginning of the function add(a, b) that in 1001 in this case
• Syntax of Function Pointer in C:

return_type (* pointer_name) (datatype_arg_1, datatype_arg_1, ...);

For example function is: float abc (int, int);


// function pointer declaration
float (*xyz_pointer) (int, int);

/*assigning the address of the function (foo) to function pointer*/


xyz_pointer = abc;
Calling a Function Through a Function Pointer in C
• Calling a function using a pointer is similar to calling a function in the usual way using the name of the function.

• Suppose we declare a function and its pointer as given below: int length = 5;
int areaSquare (int); // function declaration // Different ways to call the function
int (*pointer) (int); // function pointer declaration // 1. using function name
int area = areaSquare(length);
pointer = areaSquare;
// 2. using function pointer (a)
To call the function areaSquare, we can create a function call using int area = (*pointer)(length);
Any of the 3 ways:
// 3. using function pointer (b)
It is good practice to use the indirection operator to clear out that int area = pointer(length);
function is called using a pointer as (*pointer)()
Calling a Function Through a Function Pointer in C
#include<stdio.h> // pointing the pointer to functions memory address
fp = areaRectangle;
// function declaration
int areaRectangle(int, int); // calling the function using function pointer
area = (*fp)(length, breadth);
int main() {
int length, breadth, area; printf("Area of rectangle = %d", area);
return 0;
// function pointer declaration }
// note that our pointer declaration has identical
// arguments as the function it will point to // function definition
int (*fp)(int, int); int areaRectangle(int l, int b) {
int area_of_rectangle = l * b; Enter length and breadth of a
printf("Enter length and breadth of a rectangle\n"); return area_of_rectangle; rectangle
scanf("%d%d", &length, &breadth); } 59
Area of rectangle = 45
Passing A function's address as an Argument to other Function
function
• We cannot pass the function as an argument to another function.
• But we can pass the reference of a function as a parameter by using a function pointer.
• This process is known as call by reference as the function parameter is passed as a pointer that
holds the address of arguments.
• Therefore, C programming allows you to create a pointer pointing to the function, which can be
further passed as an argument to the function.
Function Pointer passed as an Argument
int cube(int a) { // sum = 2^2 + 3^2, as fp points to
#include<stdio.h>
// function return cubic power of a number sqaure()
return a * a * a; int sum = conditionalSum(2, 3, fp);
int conditionalSum(int a, int b,int (*ptr)())
} printf("Square sum = %d\n", sum);
{
// modify the arguments according to the
int main() { // point function pointer to cube()
//condition of the function ptr points to
int (*fp)(int); fp = cube;
a = (*ptr)(a);
// point function pointer to function square()
b = (*ptr)(b);
fp = square; // sum = 2^3 + 3^3, as fp points to
return a + b; function cube()
// sum = 2^2 + 3^2, as fp points to sqaure() sum = conditionalSum(2, 3, fp);
}
int sum = conditionalSum(2, 3, fp); printf("Cubic sum = %d", sum);
printf("Square sum = %d\n", sum); return 0;
int square(int a) {
// function return square power of a number }
// point function pointer to function cube() Square sum = ?
return a * a;
fp = cube; Cubic sum = ?
}
Types of Pointer function
• The type of a pointer to a function is based on both the return type and parameter types of the function

• There are majorly four types of pointers, they are:

• Null Pointer - If you assign a NULL value to a pointer during its declaration, it is called Null Pointer.
Syntax: int *var = NULL;

• Void Pointer – When a pointer is declared with a void keyword, then it is called a void pointer. To print the
value of this pointer, you need to typecast it.

Syntax: void *var; E.g. int a=2; void *ptr; ptr=&a; printf(“Typecasting a=%d”, *(int *)ptr);
Types of Pointer function
• Wild Pointer – A wild pointer is only declared but not assigned an address of any variable. They are very tricky
and cause segmentation errors
Types of Pointer function
• Dangling Pointer – Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this
memory, then this p is called a Dangling pointer
• You can deallocate a memory using free() function
Recursion:
• Recursion is the process in which a function calls itself up to n-number of times.
• If a program allows the user to call a function inside the same function recursively, the procedure is called a
recursive call of the function

void recursion()
{
recursion(); //The recursive function calls itself inside the same function
}

int main()
{
recursion(); //function call
}
Types of Recursion
• Following are the types of the recursion in C programming language, as follows:

1.Direct Recursion
2.Indirect Recursion
3.Tail Recursion
4.No Tail/ Head Recursion
5.Tree Recursion
Direct Recursion
• When a function calls itself within the same function repeatedly, it is called the direct recursion.
In-Direct Recursion
• When a function is mutually called by another function in a circular manner, the function is called an indirect recursion
function.
In this structure, there are four functions, fun1(), fun2(),
fun3() and fun4().

When the fun1() function is executed, it calls the fun2() for its
execution.

And then, the fun2() function starts its execution calls the
fun3() function.

In this way, each function leads to another function to makes


their execution circularly.

And this type of approach is called indirect recursion.


Tail Recursion
• A recursive function is called the tail-recursive if the function makes recursive calling itself, and that recursive call is the last
statement executes by the function. After that, there is no function or statement is left to call the recursive function
Non-Tail/Head Recursion
• A function is called the non-tail or head recursive if a function makes a recursive call itself, the recursive call will be the first
statement in the function. It means there should be no statement or operation is called before the recursive calls.
Tree Recursion
• A function is called the tree recursion, in which the function makes more than one call to itself within the recursive function.
Storage classes:
• Storage classes in C are used to determine the lifetime, visibility, memory
location, and initial value of a variable. There are four types of storage classes
in C:

•Automatic
•External
•Static
•Register
Automatic
•Automatic variables are allocated memory automatically at runtime.

•The visibility of the automatic variables is limited to the block in which they are defined.

•The scope of the automatic variables is limited to the block in which they are defined.

•The automatic variables are initialized to garbage by default.

•The memory assigned to automatic variables gets freed upon exiting from the block.

•The keyword used for defining automatic variables is auto.

•Every local variable is automatic in C by default.


Automatic
Static

• Static local variables are visible only to the function or the block in which they are defined.

• A same static variable can be declared many times but can be assigned at only one time.

• Default initial value of the static integral variable is 0 otherwise null.

• The visibility of the static global variable is limited to the file in which it has declared.

• The keyword used to define static variable is static.


Static
Register
• The variables defined as the register is allocated the memory into the CPU registers depending upon the size of the
memory remaining in the CPU.

• We can not dereference the register variables, i.e., we can not use &operator for the register variable

• The access time of the register variables is faster than the automatic variables.

• The initial default value of the register local variables is 0.

• The register keyword is used for the variable which should be stored in the CPU register.
Register
External
• The external storage class is used to tell the compiler that the variable defined as extern is declared with an
external linkage elsewhere in the program.

• The variables declared as extern are not allocated any memory. It is only declaration and intended to specify that
the variable is declared elsewhere in the program.

• The default initial value of external integral type is 0 otherwise null.

• We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block or
method.

• An external variable can be declared many times but can be initialized at only once.
External
External
External

You might also like