0% found this document useful (0 votes)
15 views

C Functions

C language full explanation chapter wise

Uploaded by

kngaravind54
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C Functions

C language full explanation chapter wise

Uploaded by

kngaravind54
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

C Functions

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.
In this article, we will learn about functions, function
definition. declaration, arguments and parameters, return
values, and many more.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. 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);
The parameter name is not mandatory while declaring
functions. We can also declare the function without using the
name of the data variables.
Example
int sum(int a, int b); // Function
declaration with parameter names
int sum(int , int); // Function
declaration without parameter names

Function Declaration
Note: A function in C must always be declared globally
before calling it.
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).
A C function is generally defined and declared in a single step
because the function definition always starts with the function
declaration so we do not need to declare it explicitly. The
below example serves as both a function definition and a
declaration.
return_type function_name (para1_type
para1_name, para2_type para2_name)
{
// body of the function
}

Function Definition in C
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 of function in C
Note: Function call is neccessary to bring the program control
to the function definition. If not called, the function
statements will not be executed.
Example of C Function
// C program to show function
// call and definition
#include <stdio.h>

// Function that takes two parameters


// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
return a + b;
}

// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);

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


return 0;
}

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
To know more about function Arguments and Return values
refer to the article – Function Arguments & Return Values in
C.
How Does C Function Work?
Working of the C function can be broken into the following
steps as mentioned below:
1. 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.
2. Defining a function:
3. Calling the function: Calling the function is a step
where we call the function by passing the arguments in
the function.
4. Executing the function: Executing the function is a step
where we can run all the statements inside the function to
get the final result.
5. 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:
1. Library Functions
2. User Defined Functions
Types of Functions in C
1. Library Function
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.

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.
Example:
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>

// Driver code
int main()
{
double Number;
Number = 49;

// Computing the square root with


// the help of predefined C
// library function
double squareRoot = sqrt(Number);

printf("The Square root of %.2lf =


%.2lf",
Number, squareRoot);
return 0;
}

Output
The Square root of 49.00 = 7.00

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.
Example:
// C program to show
// user-defined functions
#include <stdio.h>

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;
}

Output
Sum is: 70
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.

Passing Parameters to Functions


We can pass arguments to the C function in two ways:
1. Pass by Value
2. Pass by Reference
1. Pass 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.
Example:
// C program to show use
// of call by value
#include <stdio.h>

void swap(int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}

// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and
var2 is: %d, %d\n",
var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and
var2 is: %d, %d",
var1, var2);
return 0;
}

Output
Before swap Value of var1 and var2 is: 3,
2
After swap Value of var1 and var2 is: 3,
2

2. Pass 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.
Example:
// C program to show use of
// call by Reference
#include <stdio.h>

void swap(int *var1, int *var2)


{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}

// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and
var2 is: %d, %d\n",
var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and
var2 is: %d, %d",
var1, var2);
return 0;
}

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:
1. The function can reduce the repetition of the same
statements in the program.
2. The function makes code readable by providing
modularity to our program.
3. There is no fixed number of calling functions it can be
called as many times as you want.
4. The function reduces the size of the program.
5. 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:
1. Cannot return multiple values.
2. Memory and time overhead due to stack frame allocation
and transfer of program control.
Conclusion
In this article, we discussed the following points about the
function as mentioned below:
1. The function is the block of code that can be reused as
many times as we want inside a program.
2. To use a function we need to call a function.
3. Function declaration includes function_name, return
type, and parameters.
4. Function definition includes the body of the function.
5. The function is of two types user-defined function and
library function.
6. In function, we can according to two types call by value
and call by reference according to the values passed.

What is Recursion in C?
First, let’s start with the recursion definition,
Recursion is the process of a function calling itself repeatedly
till the given condition is satisfied. A function that calls itself
directly or indirectly is called a recursive function and such
kind of function calls are called recursive calls.
In C, recursion is used to solve complex problems by breaking
them down into simpler sub-problems. We can solve large
numbers of problems using recursion in C. For example,
factorial of a number, generating Fibonacci series, generating
subsets, etc.
Let’s discuss some basic terminologies and fundamentals of
recursion before going into working and implementation.
Recursive Functions in C
In C, a function that calls itself is called Recursive Function.
The recursive functions contain a call to themselves
somewhere in the function body. Moreover, such functions
can contain multiple recursive calls.
Basic Structure of Recursive Functions
The basic syntax structure of the recursive functions is:
type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}
Basic Structure of Recursive Function in C

C program to implement binary search using recursive


call
#include <stdio.h>
int recursiveBinarySearch(int array[],
int start_index, int end_index, int
element){
if (end_index >= start_index){
int middle = start_index +
(end_index - start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] > element)
return
recursiveBinarySearch(array, start_index,
middle-1, element);
return recursiveBinarySearch(array,
middle+1, end_index, element);
}
return -1;
}
int main(void){
int array[] = {1, 4, 7, 9, 16, 56,
70};
int n = 7;
int element = 9;
int found_index =
recursiveBinarySearch(array, 0, n-1,
element);
if(found_index == -1 ) {
printf("Element not found in the
array ");
}
else {
printf("Element found at index :
%d",found_index);
}
return 0;
}

Result:
Element found at index : 3

Pointers are one of the core components of the C


programming language. A pointer can be used to store the
memory address of other variables, functions, or even other
pointers. The use of pointers allows low-level memory access,
dynamic memory allocation, and many other functionality in
C.
In this article, we will discuss C pointers in detail, their types,
uses, advantages, and disadvantages with examples.
What is a Pointer in C?
A pointer is defined as a derived data type that can store the
address of other C variables or a memory location. We can
access and manipulate the data stored in that memory location
using pointers.
As the pointers in C store the memory addresses, their size is
independent of the type of data they are pointing to. This size
of pointers in C only depends on the system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in
C, but we use the ( * ) dereferencing operator in the pointer
declaration.
datatype * ptr;

where
 ptr is the name of the pointer.

 datatype is the type of data it is pointing to.


The above syntax is used to define a pointer to a variable. We
can also define pointers to functions, structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
1. Pointer Declaration

2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not
initialize it. To declare a pointer, we use the ( * ) dereference
operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory
address as it is not initialized. Such pointers are called wild
pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some
initial value to the pointer variable. We generally use the ( & )
addressof operator to get the memory address of a variable
and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;

We can also declare and initialize the pointer in a single step.


This method is called pointer definition as the pointer is
declared and initialized at the same time.
Example
int *ptr = &var;

Note: It is recommended that the pointers should always be


initialized to some value before starting using it. Otherwise, it
may lead to number of errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value
stored in the memory address specified in the pointer. We use
the same ( * ) dereferencing operator that we used in the
pointer declaration.
Dereferencing a Pointer in C
C Pointer Example
// C program to illustrate Pointers
#include <stdio.h>

void geeks()
{
int var = 10;

// declare pointer variable


int* ptr;

// note that data type of ptr and var


must be same
ptr = &var;
// assign the address of a variable
to a pointer
printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n",
*ptr);
}

// Driver program
int main()
{
geeks();
return 0;
}

Output
Value at ptr = 0x7ffca84068dc
Value at var = 10
Value at *ptr = 10

Types of Pointers in C
Pointers in C can be classified into many different types based
on the parameter on which we are defining their types. If we
consider the type of variable stored in the memory location
pointed by the pointer, then the pointers can be classified into
the following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the
integer values.
Syntax
int *ptr;
These pointers are pronounced as Pointer to Integer.
Similarly, a pointer can point to any primitive data type. It can
point also point to derived data types such as arrays and user-
defined data types such as structures.
2. Array Pointer
Pointers and Array are closely related to each other. Even the
array name is the pointer to its first element. They are also
known as Pointer to Arrays. We can create a pointer to an
array using the given syntax.
Syntax
char *ptr = &array_name;
Pointer to Arrays exhibits some interesting properties which
we discussed later in this article.
3. Structure Pointer
The pointer pointing to the structure type is called Structure
Pointer or Pointer to Structure. It can be declared in the same
way as we declare the other primitive data types.
Syntax
struct struct_name *ptr;
In C, structure pointers are used in data structures such as
linked lists, trees, etc.
4. Function Pointers
Function pointers point to the functions. They are different
from the rest of the pointers in the sense that instead of
pointing to the data, they point to the code. Let’s consider a
function prototype – int func (int, char), the function pointer
for this function will be
Syntax
int (*ptr)(int, char);
Note: The syntax of the function pointers changes according
to the function prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory
address of another pointer. Such pointers are called double-
pointers or pointers-to-pointer. Instead of pointing to a data
value, they point to another pointer.
Syntax
datatype ** pointer_name;

Dereferencing Double Pointer


*pointer_name; // get the address stored
in the inner level pointer
**pointer_name; // get the value pointed
by inner level pointer
Note: In C, we can create multi-level pointers with any
number of levels such as – ***ptr3, ****ptr4, ******ptr5 and
so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any
memory location. They can be created by assigning a NULL
value to the pointer. A pointer of any type can be assigned the
NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers
currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means
that they do not have any associated data type. They are also
called generic pointers as they can point to any type and can
be typecasted to any type.
Syntax
void * pointer_name;
One of the main properties of void pointers is that they cannot
be dereferenced.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized
with something yet. These types of C-pointers can cause
problems in our programs and can eventually cause them to
crash. If values is updated using wild pointers, they could
cause data abort or data corruption.
Example
int *ptr;
char *str;

9. Constant Pointers
In constant pointers, the memory address stored inside the
pointer is constant and cannot be modified once it is defined.
It will always point to the same memory address.
Syntax
data_type * const pointer_name;

10. Pointer to Constant


The pointers pointing to a constant value that cannot be
modified are called pointers to a constant. Here we can only
access the data pointed by the pointer, but cannot modify it.
Although, we can change the address stored in the pointer to
constant.
Syntax
const data_type * pointer_name;

Other Types of Pointers in C:


There are also the following types of pointers available to use
in C apart from those specified above:
 Far pointer: A far pointer is typically 32-bit that can
access memory outside the current segment.
 Dangling pointer: A pointer pointing to a memory
location that has been deleted (or freed) is called a
dangling pointer.
 Huge pointer: A huge pointer is 32-bit long containing
segment address and offset address.
 Complex pointer: Pointers with multiple levels of
indirection.
 Near pointer: Near pointer is used to store 16-bit
addresses means within the current segment on a 16-bit
machine.
 Normalized pointer: It is a 32-bit pointer, which has as
much of its value in the segment register as possible.
 File Pointer: The pointer to a FILE data type is called a
stream pointer or a file pointer.
Size of Pointers in C
The size of the pointers in C is equal for every pointer type.
The size of the pointer does not depend on the type it is
pointing to. It only depends on the operating system and CPU
architecture. The size of pointers in C is
 8 bytes for a 64-bit System

 4 bytes for a 32-bit System


The reason for the same size is that the pointers store the
memory addresses, no matter what type they are. As the space
required to store the addresses of the different memory
locations is the same, the memory required by one pointer
type will be equal to the memory required by other pointer
types.
How to find the size of pointers in C?
We can find the size of pointers using the sizeof operator as
shown in the following program:
Example: C Program to find the size of different pointer
types.
// C Program to find the size of
different pointers types
#include <stdio.h>

// dummy structure
struct str {
};

// dummy function
void func(int a, int b){};

int main()
{
// dummy variables definitions
int a = 10;
char c = 'G';
struct str x;

// pointer definitions of different


types
int* ptr_int = &a;
char* ptr_char = &c;
struct str* ptr_str = &x;
void (*ptr_func)(int, int) = &func;
void* ptr_vn = NULL;

// printing sizes
printf("Size of Integer Pointer
\t:\t%d bytes\n",
sizeof(ptr_int));
printf("Size of Character
Pointer\t:\t%d bytes\n",
sizeof(ptr_char));
printf("Size of Structure
Pointer\t:\t%d bytes\n",
sizeof(ptr_str));
printf("Size of Function
Pointer\t:\t%d bytes\n",
sizeof(ptr_func));
printf("Size of NULL Void
Pointer\t:\t%d bytes",
sizeof(ptr_vn));

return 0;
}

Output
Size of Integer Pointer : 8 bytes
Size of Character Pointer : 8 bytes
Size of Structure Pointer : 8 bytes
Size of Function Pointer : 8 bytes
Size of NULL Void Pointer : 8 bytes
As we can see, no matter what the type of pointer it is, the size
of each and every pointer is the same.
Now, one may wonder that if the size of all the pointers is the
same, then why do we need to declare the pointer type in the
declaration? The type declaration is needed in the pointer
for dereferencing and pointer arithmetic purposes.
C Pointer Arithmetic
The Pointer Arithmetic refers to the legal or valid arithmetic
operations that can be performed on a pointer. It is slightly
different from the ones that we generally use for mathematical
calculations as only a limited set of operations can be
performed on pointers. These operations include:
 Increment in a Pointer

 Decrement in a Pointer

 Addition of integer to a pointer

 Subtraction of integer to a pointer

 Subtracting two pointers of the same type

 Comparison of pointers of the same type.


 Assignment of pointers of the same type.
// C program to illustrate Pointer
Arithmetic

#include <stdio.h>

int main()
{

// Declare an array
int v[3] = { 10, 100, 200 };

// Declare pointer variable


int* ptr;
// Assign the address of v[0] to ptr
ptr = v;

for (int i = 0; i < 3; i++) {

// print value at address which


is stored in ptr
printf("Value of *ptr = %d\n",
*ptr);

// print value of ptr


printf("Value of ptr = %p\n\n",
ptr);

// Increment pointer ptr by 1


ptr++;
}
return 0;
}

Output
Value of *ptr = 10
Value of ptr = 0x7ffcfe7a77a0

Value of *ptr = 100


Value of ptr = 0x7ffcfe7a77a4

Value of *ptr = 200


Value of ptr = 0x7ffcfe7a77a8

C Pointers and Arrays


In C programming language, pointers and arrays are closely
related. An array name acts like a pointer constant. The value
of this pointer constant is the address of the first element. For
example, if we have an array named val then val and &val[0]
can be used interchangeably.
If we assign this value to a non-constant pointer of the same
type, then we can access the elements of the array using this
pointer.
Example 1: Accessing Array Elements using Pointer with
Array Subscript

// C Program to access array elements


using pointer
#include <stdio.h>

void geeks()
{
// Declare an array
int val[3] = { 5, 10, 15 };

// Declare pointer variable


int* ptr;
// Assign address of val[0] to ptr.
// We can use ptr=&val[0];(both are
same)
ptr = val;

printf("Elements of the array are:


");

printf("%d, %d, %d", ptr[0], ptr[1],


ptr[2]);

return;
}

// Driver program
int main()
{
geeks();
return 0;
}

Output
Elements of the array are: 5, 10, 15

Not only that, as the array elements are stored continuously,


we can pointer arithmetic operations such as increment,
decrement, addition, and subtraction of integers on pointer to
move between array elements.
Example 2: Accessing Array Elements using Pointer
Arithmetic
// C Program to access array elements
using pointers
#include <stdio.h>

int main()
{

// defining array
int arr[5] = { 1, 2, 3, 4, 5 };

// defining the pointer to array


int* ptr_arr = arr;

// traversing array using pointer


arithmetic
for (int i = 0; i < 5; i++) {
printf("%d ", *ptr_arr++);
}
return 0;
}

Output
1 2 3 4 5
This concept is not limited to the one-dimensional array, we
can refer to a multidimensional array element as well using
pointers.
To know more about pointers to an array, refer to this article –
Pointer to an Array
Uses of Pointers in C
The C pointer is a very powerful tool that is widely used in C
programming to perform various useful operations. It is used
to achieve the following functionalities in C:
1. Pass Arguments by Reference

2. Accessing Array Elements


3. Return Multiple Values from Function

4. Dynamic Memory Allocation

5. Implementing Data Structures

6. In System-Level Programming where memory addresses


are useful.
7. In locating the exact value at some memory location.
8. To avoid compiler confusion for the same variable
name.
9. To use in Control Tables.
Advantages of Pointers
Following are the major advantages of pointers in C:
 Pointers are used for dynamic memory allocation and
deallocation.
 An Array or a structure can be accessed efficiently with
pointers

 Pointers are useful for accessing memory locations.

 Pointers are used to form complex data structures such


as linked lists, graphs, trees, etc.
 Pointers reduce the length of the program and its
execution time as well.
Disadvantages of Pointers
Pointers are vulnerable to errors and have following
disadvantages:
 Memory corruption can occur if an incorrect value is
provided to pointers.

 Pointers are a little bit complex to understand.

 Pointers are majorly responsible for memory leaks in C.

 Pointers are comparatively slower than variables in C.


 Uninitialized pointers might cause a segmentation fault.

Conclusion
In conclusion, pointers in C are very capable tools and
provide C language with its distinguishing features, such as
low-level memory access, referencing, etc. But as powerful as
they are, they should be used with responsibility as they are
one of the most vulnerable parts of the language.

You might also like