Unit 5
Unit 5
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
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.
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.
5
UNIT-5 Functions in C
Language
‘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
}
int z = x + y;
return z;
}
The arguments x and y in this function definition are the formal arguments.
Open Compiler
#include <stdio.h>
int z = x + y;
return z;
}
int main(){
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.
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 :
Reallocate memory that is the same size as the object that was supplied into the function.
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
Open Compiler
#include <stdio.h>
int main(){
int x = 10;
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
Open Compiler
1
1
UNIT-5 Functions in C
Language
#include <stdio.h>
int main(){
int x = 10;
int *y = &x;
x: 10 Address of x: -1742755108
Address of y: -1742755104
Value at address in y: 10
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 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 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.
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>
int z;
return 0;
}
int main(){
return 0;
}
Output
When you run this code, it will produce the following output −
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 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