0% found this document useful (0 votes)
16 views19 pages

FUNCTIONS in C

The document provides a comprehensive overview of functions in C, detailing their syntax, types, advantages, and disadvantages. It explains concepts such as function declaration, definition, calling, recursion, and parameter passing methods (by value and by reference). Additionally, it covers pointers, storage classes, arrays of pointers, and function pointers, highlighting their significance in C programming.

Uploaded by

Abraham Abraham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views19 pages

FUNCTIONS in C

The document provides a comprehensive overview of functions in C, detailing their syntax, types, advantages, and disadvantages. It explains concepts such as function declaration, definition, calling, recursion, and parameter passing methods (by value and by reference). Additionally, it covers pointers, storage classes, arrays of pointers, and function pointers, highlighting their significance in C programming.

Uploaded by

Abraham Abraham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

FUNCTIONS

A function is a block of code which only runs when it is called. You can pass
data, known as parameters, into a function. Functions are used to perform
certain actions, and they are important for reusing code: Define the code once,
and use it many times.
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);
Function Definition
The function definition consists of actual statements which are executed when
the function is called. 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 separately.
Syntax
return_type function_name (para1_type para1_name, para2_type
para2_name)
{
// body of the function
}

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.
Example of function in C

#include <stdio.h>
int sum(int a, int b)
{
return a + b;
}
int main()
{
int add = sum(10, 30);
printf("Sum is: %d", add);
return 0;
}

Output
Sum is: 40
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);

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

Advantages of Functions in C
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.
Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions
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
Main() : The execution of every C program starts from this function.
Printf() : this function is used to display the output in C.
Scanf() : this function is used for taking the input in C.
2. User Defined Function
Functions that the programmer creates are known as “User-Defined functions”.
User-defined functions can be 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.
Example :
#include <stdio.h>
int sum(int a, int b)
{
return a + b;
}
int main()
{
int a = 30, b = 40;
int result = sum(a, b);
printf("Sum is: %d", result);
return 0;
}
Output
Sum is: 70
Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how
it works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:
Example
int sum(int k);
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all
numbers smaller than k and returns the result. When k becomes 0, the
function just returns 0.
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act as
variables inside the function.
Parameters are specified after the function name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma (,).
Syntax
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

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.

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 of the function. In this case , any changes made to
the parameters inside the functions have no effect on the actual parameters.
Example:

#include <stdio.h>
void swap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}
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
2. Pass by Reference
This method copies the address of an actual paramteres into the formal
parameters. Inside the function , the address is used to access the actual
parameters used in the call. This mean that changes made to the parameter
affect the actual parameters.
Example:
#include <stdio.h>
void swap(int *var1, int *var2)
{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
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
Local variable
A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function:
Example
void myFunction() {
// Local variable that belongs to myFunction
int x = 5;
// Print the variable x
printf("%d", x);
}
int main() {
myFunction();
return 0;
}
A local variable cannot be used outside the function it belongs to.

Global Scope
A variable created outside of a function, is called a global variable and belongs
to the global scope.
Global variables are available from within any scope, global and local:
Example
A variable created outside of a function is global and can therefore be used by
anyone:

int x = 5;
void myFunction() {
printf("%d", x);
}
int main() {
myFunction();
printf("%d", x);
return 0;
}
C pointers
A pointer is a variable that stores the memory address of another variable.
Instead of holding a direct value, it holds the address where the value is stored
in memory. There are 2 important operators that we will use in pointers
concepts i.e.
• Dereferencing operator(*) used to declare pointer variable and access
the value stored in the address.
• Address operator(&) used to returns the address of a variable or to
access the address of a variable to a pointer.
Example :
#include <stdio.h>

int main()
{
int m = 100;
int *ptr = &m;
printf("The Value of Variable m is: %d\n", m);
printf("The Memory Address of Variable m is: %p\n", &m);
printf("The Memory Address of Variable m is using ptr: %p\n", ptr);

return 0;
}

Output
The Value of Variable m is: 100
The Memory Address of Variable m is: 0x7ffee1eea79c
The Memory Address of Variable m is using ptr: 0x7ffee1eea79c
• Declaration: A pointer is declared using an asterisk * before the variable
name. The data type before the asterisk specifies the type of variable the
pointer can point to.
int *ptr; // Declares an integer pointer
float *fptr; // Declares a float pointer
• Initialization: Pointers are initialized with the address of a variable using
the address-of operator &.
int num = 10;
int *ptr = &num; // ptr now holds the address of num
• Dereferencing: To access the value stored at the memory location
pointed to by a pointer, the dereference operator * is used.
int num = 10;
int *ptr = &num;
printf("%d", *ptr); // Output: 10 (value of num)
• Accessing array elements: Pointers can be used to access array elements
by incrementing or decrementing the pointer.
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element of arr
printf("%d", *ptr); // Output: 1
ptr++; // ptr now points to the next element
printf("%d", *ptr); // Output: 2
• Passing pointers to functions: Pointers can be passed as arguments to
functions, allowing the function to modify the original variable.
void increment(int *n) {
(*n)++;
}
int num = 10;
increment(&num);
printf("%d", num); // Output: 11
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

C Pointer Arithmetic
The Pointer Arithmetic refers to the 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/Decrement by 1
• Addition/Subtraction of Integer
• Subtracting Two Pointers of Same Type
• Comparing/Assigning Two Pointers of Same Type
• Comparing/Assigning with NULL

STORAGE CLASSES IN C

Storage Classes in C
In C, storage classes define the lifetime, scope, and visibility of variables. They
specify where a variable is stored, how long its value is retained, and how it can
be accessed which help us to trace the existence of a particular variable during
the runtime of a program.
In C, there are four primary storage classes
• auto
• register
• static
• extern

auto
This is the default storage class for all the variables declared inside a function.
Auto variables can be only accessed within the function they have been
declared and not outside them.
Properties of auto Variables
• Scope: Local
• Default Value: Garbage Value
• Memory Location: RAM
• Lifetime: Till the end of its scope

static
This storage class is used to declare static variables that have the property of
preserving their value even after they are out of their scope! Hence, static
variables preserve the value of their last use in their scope.
Properties of static Storage Class
• Scope: Local
• Default Value: Zero
• Memory Location: RAM
• Lifetime: Till the end of the program
register
This storage class declares register variables that have the same functionality as
that of the auto variables. The only difference is that the compiler tries to store
these variables in the register of the microprocessor if a free register is
available making it much faster than any of the other variables.
Properties of register Storage Class Objects
• Scope: Local
• Default Value: Garbage Value
• Memory Location: Register in CPU or RAM
• Lifetime: Till the end of its scope
extern
Extern storage class simply tells us that the variable is defined elsewhere and
not within the same block where it is used. Basically, the value is assigned to it
in a different block and this can be overwritten/changed in a different block as
well.
Also, a normal global variable can be made extern as well by placing the
‘extern’ keyword before its declaration in any function.
Properties of extern Storage Class Objects
• Scope: Global
• Default Value: Zero
• Memory Location: RAM
• Lifetime: Till the end of the program.

Array of Pointers in C
In C, a pointer array is a homogeneous collection of indexed pointer variables
that are references to a memory location. It is generally used in C Programming
when we want to point at multiple memory locations of a similar data type in
our C program. We can access the data by dereferencing the pointer pointing
to it.
Syntax:
pointer_type *array_name [array_size];
Here,
• pointer_type: Type of data the pointer is pointing to.
• array_name: Name of the array of pointers.
• array_size: Size of the array of pointers.
Example:
// C program to demonstrate the use of array of pointers
#include <stdio.h>

int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;

// array of pointers to integers


int* ptr_arr[3] = { &var1, &var2, &var3 };

// traversing using loop


for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);
}
return 0;
}
Output
Value of var1: 10 Address: 0x7fff1ac82484
Value of var2: 20 Address: 0x7fff1ac82488
Value of var3: 30 Address: 0x7fff1ac8248c

Function Pointer in C
In C, a function pointer is a type of pointer that stores the address of a
function, allowing functions to be passed as parameters and invoked
dynamically. It is useful in techniques such as callback functions.

Example:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
// Declare a function pointer that matches
// the signature of add() fuction
int (*fptr)(int, int);
fptr = &add;
// Call the function via ptr
printf("%d", fptr(10, 5));
return 0;
}
Output
15
Function Pointer Declaration
The below is the generic syntax of function declaration:
return_type (*pointer_name)(parameter_types);
• return_type: The type of the value that the function returns.
• parameter_types: The types of the parameters the function takes.
• pointer_name: The name of the function pointer.
Initialization
A function pointer is then initialized by assigning the address of the function.
pointer_name = &function_name

#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
void calc(int a, int b, int (*op)(int, int)) {
printf("%d\n", op(a, b));
}
int main() {
calc(10, 5, add);
calc(10, 5, subtract);
return 0;
}
Output: 15, 5

You might also like