0% found this document useful (0 votes)
29 views17 pages

UNIT 5

Uploaded by

tanishqrajpatel
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)
29 views17 pages

UNIT 5

Uploaded by

tanishqrajpatel
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/ 17

A function in C is a set of statements that when called perform some specific tasks.

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
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.
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.
Note: Function call is neccessary to bring the program control to the function definition. If not called,
the function statements will not be executed.

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

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:

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:

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


specify the return types and parameters of the function.

2. Defining a function: This is where the function’s body is provided. Here, we specify what the
function does, including the operations to be performed when the function is called.

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 back
to the caller.

Types of Functions

There are two types of functions in C:

1. Library Functions

2. User Defined Functions

Library Functions

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:

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.

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

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;

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.
We can pass arguments to the C function in two ways:

1. Pass by Value

2. Pass by Reference

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

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

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

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

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.

Basics of Pointers

A pointer in C is a variable that stores the memory address of another variable. This allows direct
manipulation and access to the memory location of data. Pointers are particularly useful when you
need to pass large structures or arrays to a function, or when you want a function to modify the
value of a variable.

Declaration and Initialization

To declare a pointer, you use the asterisk symbol (*) before the pointer’s name. For example, int
*ptr; declares a pointer named ptr that can hold the address of an integer variable. To initialize a
pointer, you assign it the address of a variable using the ampersand (&) operator. For example, int
var = 10; ptr = &var;.
Pointer Syntax

The syntax for pointers can be summarized with a few key points:

• The asterisk (*) is used in declaration to denote a pointer.

• The ampersand (&) retrieves the address of a variable to be stored in a pointer.

• The asterisk (*) is also used to dereference a pointer, that is, to access or modify the value at
the memory address stored in the pointer.

Understanding Functions in C

Functions in C are used to encapsulate a block of code that performs a specific task. A function has a
declaration (prototype), a definition (the body of the function), and a call. The declaration specifies
the function’s name, return type, and parameters, while the definition contains the actual code. A
function is called by its name followed by parentheses, possibly containing arguments.

Importance of Functions in Modular Programming

Functions are the building blocks of modular programming in C. They allow developers to break
down complex problems into simpler, reusable pieces of code. This not only makes the code more
manageable and readable but also facilitates debugging and testing.

Why Use Pointers as Function Parameters

Using pointers as function parameters allows functions to modify the value of the arguments passed
to them. This is essential in scenarios where you need to update the values of variables or
manipulate large data structures without copying the entire structure. Pointers also make your
program more efficient by reducing the memory footprint and execution time.

Passing Pointers to Functions

To pass a pointer to a function, you simply specify the pointer type in the function’s parameter list.
For example:

void updateValue(int *p) {

*p = 100; // Modifies the value of the variable pointed to by p

In the calling function, you pass the address of the variable:

int main() {

int var = 20;

updateValue(&var);
// var now holds the value 100

return 0;

Passing by Reference vs. Passing by Value

When a variable is passed by value to a function, the function works with a copy of the variable, and
changes to the parameter do not affect the original variable. In contrast, passing by reference (using
pointers) means the function receives the address of the variable, allowing it to modify the variable
directly. This is crucial when your function needs to alter the input variables or deal with data too
large to be efficiently copied.

Modifying Values of Variables in Functions

To modify the value of a variable within a function, you must pass the address of the variable to the
function. This method allows the function to access and modify the variable’s value directly in its
memory location.

1#include <stdio.h>

3void modifyValue(int *val) {

4 *val = 10; // Directly modifying the value at the memory address

5}

7int main() {

8 int a = 5;

9 printf("Original value of a: %d\n", a);

10 modifyValue(&a);

11 printf("Modified value of a: %d\n", a);


12 return 0;

13 }

Working with Array Elements in Functions

Arrays in C are closely related to pointers. When you pass an array to a function, you are essentially
passing a pointer to its first element. This characteristic allows functions to iterate over array
elements using pointer arithmetic, modifying them if needed.

1#include <stdio.h>

3void doubleArray(int *arr, int length) {

4 for(int i = 0; i < length; i++) {

5 *(arr + i) *= 2; // Doubling each element

6 }

7}

9int main() {

10 int numbers[] = {1, 2, 3, 4, 5};

11 int length = sizeof(numbers) / sizeof(numbers[0]);

12 doubleArray(numbers, length);

13 for(int i = 0; i < length; i++) {

14 printf("%d ", numbers[i]);


15 }

16 return 0;

17 }

Returning Pointers from Functions

Functions in C can return pointers, enabling dynamic memory allocation and the creation of complex
data structures. However, it is crucial to ensure that the memory pointed to by the returned pointer
remains valid after the function call.

Dynamic Memory Allocation

Using malloc and free is essential when dealing with dynamic memory allocation. When a function
returns a pointer to dynamically allocated memory, you must ensure to free that memory when it’s
no longer needed to avoid memory leaks.

1#include <stdio.h>

2#include <stdlib.h>

4int* createArray(int size) {

5 int* arr = (int*)malloc(size * sizeof(int));

6 if(arr != NULL) {

7 for(int i = 0; i < size; i++) {

8 arr[i] = i * i; // Example initialization

9 }

10 }

11 return arr;
12}

13

14int main() {

15 int *myArray = createArray(5);

16 if(myArray != NULL) {

17 for(int i = 0; i < 5; i++) {

18 printf("%d ", myArray[i]);

19 }

20 free(myArray);

21 }

22 return 0;

23 }

Avoiding Pitfalls

Common pitfalls include returning pointers to local variables and not managing allocated memory
correctly, leading to dangling pointers and memory leaks. Always ensure the memory you return has
a lifetime beyond the function’s scope and is properly freed when no longer needed.

Best Practices for Using Pointers in Functions

• Always check pointer parameters for NULL before dereferencing.

• Use const with pointer parameters if you don’t need to modify the input data, enhancing
code clarity and safety.

• Clearly document whether the caller or callee is responsible for allocating and deallocating
memory.

You might also like