0% found this document useful (0 votes)
10 views18 pages

Unit 5

This document provides an overview of functions in the C programming language, explaining their definition, importance, types (library and user-defined), and how to use them. It details the steps involved in declaring, defining, and calling functions, as well as the concepts of actual and formal parameters, and the techniques for passing arguments (call by value and call by reference). Additionally, it discusses the advantages and disadvantages of each parameter passing technique and provides examples to illustrate the concepts.

Uploaded by

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

Unit 5

This document provides an overview of functions in the C programming language, explaining their definition, importance, types (library and user-defined), and how to use them. It details the steps involved in declaring, defining, and calling functions, as well as the concepts of actual and formal parameters, and the techniques for passing arguments (call by value and call by reference). Additionally, it discusses the advantages and disadvantages of each parameter passing technique and provides examples to illustrate the concepts.

Uploaded by

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

UNIT-5 Functions in C

Language
What is a Function?
A function is a block of statements that performs a specific task. Suppose we are
building an application in C language and in one of our program, we need to perform
a same task more than once. In such case we have two options:
 Use the same set of statements every time we want to perform the task
 Create a function to perform that task, and just call it every time we need to
perform that task. Here option (b) is obviously a good practice.
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.
Importance functions in C:
Functions are used because of following reasons –
 To improve the readability of code.
 Improves the reusability of the code, same function can be used in any
program rather than writing the same code again.
 Debugging of the code would be easier if we use functions, as errors are easy to
be traced.
 Reduces the size of the code, duplicate set of statements are replaced by function
calls.

Types of functions:
1) Predefined standard library functions – such as puts(), gets(), printf(), scanf() etc –
These are the functions which already have a definition in header files (.h files like
stdio.h).
2) User Defined functions – The functions that we create in a program are known as user
defined functions.
Library Functions in C
C offers a number of library functions included in different header files. For example,
the stdio.h header file includes printf() and scanf() functions. Similarly,
the math.h header file includes a number of functions such as sin(), pow(), sqrt() and
more.

These functions perform a predefined task and can be called upon in any program as per
requirement. However, if you don't find a suitable library function to serve your purpose,
you can define one.

1
UNIT-5 Functions in C
Language

How to use a function?


To use a function the following three steps we need to follow:

Function declaration/ prototype: A function prototype is simply the declaration of a


function that specifies function's name, parameters and return type. It doesn't contain
function body. A function prototype gives information to the compiler that the function
may later be used in the program.
Syntax:
return_type function_name (data_type parameter...)
{
//code to be executed
}

Function call: Function can be called from anywhere in the program. The parameter
list must be same in function calling and function declaration. We must pass the same
number of parameters as it is declared in the function declaration.
Syntax: function_name (argument_list);

While creating a C function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task.

To call a function properly, you need to comply with the declaration of the function
prototype. If the function is defined to receive a set of arguments, the same number and
type of arguments must be passed.

When a function is defined with arguments, the arguments in front of the function name
are called formal arguments. When a function is called, the arguments passed to it are
the actual arguments.

When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is
2
UNIT-5 Functions in C
Language
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.

Function definition: It contains the actual statements which are to be executed. It is


the most important aspect to which the control comes when the function is called.
Here, we must notice that only one value can be returned from the function. It is also
called function body part.
Syntax: return_type function_name (argument list)
{
//function body;
}

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
3
UNIT-5 Functions in C
Language
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:
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

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.

4
UNIT-5 Functions in C
Language
 C library functions save a lot of time i.e, function development time.
 C library functions are convenient as they always work.

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.

5
UNIT-5 Functions in C
Language

Passing arguments to a function:


In programming, argument refers to the variable passed to the function. In the example
below, two variables n1 and n2 are passed during the function call. The parameters,
‘a’ and ‘b’ accepts the arguments in the function definition. These arguments are
called formal parameters of the function.

‘return’ Statement:

The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after the
return statement. In the example shown below, the value of the result variable is
returned to the main() function. The sum variable in the main() function is assigned
this value.

6
UNIT-5 Functions in C
Language

7
UNIT-5 Functions in C
Language
Actual Parameters and Formal Parameters:

Actual Parameters: The values/variables passed while calling a function are called
actual parameters.
Formal Parameters: These are the variables declared in function
definition/prototype, and receive their values when a call to that function is made.
The value(s) of the actual parameters are copied to formal parameters when the call
to that function is made. The following example shows it clearly.

#include<stdio.h>
int sum(int a, int b) //Function definition, here a and b are formal parameters
{
return a+b;
}
void main()
{
int x=10,y=20;
int s = sum(x,y); //Function call, here x and y are actual parameters
}

Parameter passing techniques:


There are two techniques through which we can pass parameters to a function:
 Call by Value
 Call by Reference

Call by value: In call by value, a copy of actual arguments is passed to formal


arguments of the called function and any change made to the formal arguments in the
8
UNIT-5 Functions in C
Language
called function have no effect on the values of actual arguments in the calling function.

Take a look at the following snippet −

type function_name(type var1, type var2, ...)


Here, the argument variables are called the formal arguments. Inside the function’s scope, these
variables act as its local variables.

Consider the following function −

int add(int x, int y){

int z = x + y;

return z;

}
The arguments x and y in this function definition are the formal arguments.

Example: Call by Value in C


If the add() function is called, as shown in the code below, then the variables inside the parenthesis
(a and b) are the actual arguments. They are passed to the function.

Take a look at the following example −

Open Compiler
#include <stdio.h>

int add(int x, int y){

int z = x + y;

return z;
}

int main(){

int a = 10, b = 20;

int c = add(a, b);

printf("Addition: %d", c);


}
9
UNIT-5 Functions in C
Language
Output

When you run this code, it will produce the following output −

Addition: 30

The Call by Value method implies that the values of the actual arguments are copied in the formal
argument variables. Hence, "x" takes the value of "a" and "b" is assigned to "y". The local variable "z"
inside the add() function stores the addition value. In the main() function, the value returned by the add()
function is assigned to "c", which is printed.

Note that a variable in C language is a named location in the memory. Hence, variables are created in
the memory and each variable is assigned a random memory address by the compiler.

How Does "Call by Value" Work in C?


Let us assume that the variables a, b and c in the main() function occupy the memory locations 100, 200
and 300 respectively. When the add() function is called with a and b as actual arguments, their values
are stored in x and y respectively.

The variables x, y, and z are the local variables of the add() function. In the memory, they will be
assigned some random location. Let's assume that they are created in memory address 1000, 2000 and
3000, respectively.
Since the function is called by copying the value of the actual arguments to their corresponding formal
argument variables, the locations 1000 and 2000 which are the address of x and y will hold 10 and 20,
respectively. The compiler assigns their addition to the third local variable z which is returned.
As the control comes back to the main() function, the returned data is assigned to c, which is displayed
as the output of the program.
Advantages of Call by value :

 Passing by value eliminates a function’s potential side effects, making your software simpler to
maintain and understand.

 Reduce the likelihood of introducing subtle issues that are challenging to monitor.
1
0
UNIT-5 Functions in C
Language
Disadvantages of Call By value :

 Copying large objects will effect the performance.

 Reallocate memory that is the same size as the object that was supplied into the function.

Call by reference: In call by reference, the location (address) of actual arguments is


passed to formal arguments of the called function. This means by accessing the
addresses of actual arguments we can alter them within from the called function.

The Address Operator (&) in C

In C language, a variable is a named memory location. When a variable declared, the compiler allocates
a random location in the memory and internally identifies the location with the user-defined name.

To fetch the address at which the variable has been created, we use the address (&) operator.

Example

Take a look at the following example −

Open Compiler
#include <stdio.h>

int main(){

int x = 10;

printf("x: %d Address of x: %d", x, &x);


}
Output
This will print the value of x and its address −
x: 10 Address of x: -1990957196

What is a Pointer in C?
A pointer is a variable that stores the address of another variable. To declare a pointer variable, its name
is prefixed with the * symbol. The type of the pointer variable and its host variable must be same.
The address is assigned with the & operator. The dereference operator (*) is used with the pointer. It
fetches the value of a variable whose address is assigned to the pointer.

Example

The following example demonstrates how referening and dereferencing work in C −

Open Compiler

1
1
UNIT-5 Functions in C
Language
#include <stdio.h>

int main(){

int x = 10;
int *y = &x;

printf("x: %d Address of x: %d\n", x, &x);


printf("Address of y: %d \n", &y);
printf("Value at address in y: %d\n", *y);
}
Output

Run the code and check its output −

x: 10 Address of x: -1742755108
Address of y: -1742755104
Value at address in y: 10

How Does Call by Reference Work in C?

When a function is called by reference, the address of the actual argument variables passed, instead of
their values.

Let us define the add() function that receives the references of two variables −

int add(int *x, int *y){

int z = *x + *y;

return z;
}

When such a function is called, we pass the address of the actual argument.

Example

Let us call the add() function by reference from inside the main() function −

Open Compiler
#include <stdio.h>

/* function declaration */

1
2
UNIT-5 Functions in C
Language
int add(int *, int *);

int main(){

int a = 10, b = 20;


int c = add(&a, &b);

printf("Addition: %d", c);


}

int add(int *x, int *y){

int z = *x + *y;

return z;
}
Output

When you run this code, it will produce the following output −

Addition: 30
Now let's understand how this code actually works. The main() function passes the address of a and b to
the add() function. The addresses of a and b are assigned to the pointer variables x and y.
Now focus on the statement "z = *x + *y;" inside the add() function. Remember that x stores the address
of a. The dereference operator in *x and *y fetches the values of a and b respectively, hence z is the
addition of a and b in the main() function.

Example: Swap Values with Call by Reference

Let us understand in more detail how the Call by Reference mechanism works, with the help of the
following example that interchanges value of two variables.

Open Compiler
#include <stdio.h>

/* Function definition to swap the values */


/* It receives the reference of two variables whose values are to be swapped */

int swap(int *x, int *y){

int z;

z = *x; /* save the value at address x */


1
3
UNIT-5 Functions in C
Language
*x = *y; /* put y into x */
*y = z; /* put z into y */

return 0;
}

/* The main() function has two variables "a" and "b" */


/* Their addresses are passed as arguments to the swap() function. */

int main(){

/* local variable definition */


int a = 10;
int b = 20;

printf("Before swap, value of a: %d\n", a );


printf("Before swap, value of b: %d\n", b );

/* calling a function to swap the values */


swap(&a, &b);

printf("After swap, value of a: %d\n", a);


printf("After swap, value of b: %d\n", b);

return 0;
}
Output

When you run this code, it will produce the following output −

Before swap, value of a: 10


Before swap, value of b: 20
After swap, value of a: 20
After swap, value of b: 10

Explanation
Assume that the variables a and b in the main() function are allotted locations with the memory address
100 and 200 respectively. As their addresses are passed to x and y (remember that they are pointers), the
variables x, y and z in the swap() function are created at addresses 1000, 2000 and 3000 respectively.

1
4
UNIT-5 Functions in C
Language

Since "x" and "y" store the address of "a" and "b", "x" becomes 100 and "y" becomes 200, as the above
figure shows.

Inside the swap() function, the first statement "z = *x" causes the value at address in "x" to be stored in
"x" (which is 10). Similarly, in the statement "*x = *y;", the value at the address in "y" (which is 20) is
stored in the location whose pointer is "x".
Finally, the statement "*y = z;" assigns the "z" to the variable pointed to by "y", which is "b" in the
main() function. The values of "a" and "b" now get swapped.

The following figure visually demonstrates how it works −

The Call by Reference mechanism is widely used when a function needs to perform memory-level
manipulations such as controlling the peripheral devices, performing dynamic allocation, etc.

1
5
UNIT-5 Functions in C
Language
Difference between call by value and call by reference:
call by value call by reference

This method copy original value into This method copy address of
function as an argument. argument into function as an argument.
Changes made to the parameter affect
Changes made to the parameter
the argument. Because address is used
inside the function have no effect on
to access the actual argument.
the argument.
Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location

Example of call by
value: #include<stdio.h>
#include<conio.h>
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to
function printf("\nValue of a: %d",a);
printf("\nValue of b:
%d",b); getch();
}

Example of call by
reference:
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
1
6
UNIT-5 Functions in C
Language
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

1
7
UNIT-5 Functions in C
Language
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to
function printf("\nValue of a: %d",a);
printf("\nValue of b:
%d",b); getch();
}
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.
Functions in C
Visit Course

1
8

You might also like