INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
INTRODUCTION
A function is a group of statements that performs a specific task. Every C
program has at least one function, which is main().
One can break up a particular task into different blocks of code called function.
The code thus divided should be logically correct and make some sense and perform a
part of the task .
A function declaration tells the compiler about a function's name, return type,
and parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program
can call. For example, strcat() to concatenate two strings, memcpy() to copy one
memory location to another location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure,
etc.
Some important properties of Functions in C are:
Defining a Function
The general form of a function definition in C programming language is as follows
−
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and
a function body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
Function Body − The function body contains a collection of statements that define
what the function does.
Example:
Program to find maximum and minimum between two numbers using functions
/* C program to find maximum and minimum between two numbers using functions */
#include <stdio.h>
/* Function declarations */
int max(int num1, int num2);
int main( )
{
int num1, num2, maximum;
/* Input two numbers from user */
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
maximum = max(num1, num2); // Call maximum function
printf("\nMaximum = %d\n", maximum);
return 0;
}
/** Find maximum between two numbers. */
int max(int num1, int num2)
{
return (num1 > num2 ) ? num1 : num2;
}
Output :
Enter any two numbers : 10 20
Maximum = 20
Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two numbers
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
else
result = num2;
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
A function declaration has the following parts
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required,
hence a function declaration can also be done as shown below
int max (int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top
of the file calling the function.
Calling a Function
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.
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
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned
value.
For example
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
We have kept max() along with main() and compiled the source code. While running the
final executable, it would produce the following result −
Max value is : 200
Function Arguments / Parameters
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function
1. Call by value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no
effect on the argument.
2. Call by reference
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
Call by value
The call by value method of passing arguments to a function copies the actual value of
an argument into the formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the argument.
By default, C programming uses call by value to pass arguments. In general, it means
the code within a function cannot alter the arguments used to call the function. Consider
the function swap() definition as follows.
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
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;
}
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
return;
}
Let us put the above code in a single C file, compile and execute it, it will produce the
following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200
It shows that there are no changes in the values, though they had been changed inside
the function.
Call by reference
The call by reference method of passing arguments to a function copies the address of
an argument into the formal parameter. Inside the function, the address is used to
access the actual argument used in the call. It means the changes made to the
parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the functions just like
any other value. So accordingly you need to declare the function parameters as pointer
types as in the following function swap(), which exchanges the values of the two integer
variables pointed to, by their arguments.
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us now call the function swap() by passing values by reference as in the following
example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
int b = 200;
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 );
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us put the above code in a single C file, compile and execute it, to produce the
following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
It shows that the change has reflected outside the function as well, unlike call by value
where the changes do not reflect outside the function.
Scope of Variables
A scope in any programming is a region of the program where a defined variable
can have its existence and beyond that variable it cannot be accessed. There are three
places where variables can be declared in C programming language
Inside a function or a block which is called local variables.
Outside of all functions which is called global variables.
In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own. The following example
shows how local variables are used. Here all the variables a, b, and c are local to main()
function.
#include <stdio.h>
int main () {
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and they can
be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. The following program show
how global variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
A program can have same name for local and global variables but the value of
local variable inside a function will take preference. Here is an example
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
When the above code is compiled and executed, it produces the following result
value of g = 10
Formal Parameters
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must
initialize it yourself. Global variables are initialized automatically by the system when
you define them as follows
Data Type Initial Default Value
int 0
char '\0'
float 0
double 0
pointer NULL
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), printf(), scanf() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity of a
big program and optimizes the code.
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a
common place called the library. Such functions are used to perform some specific
operations.
For example, printf is a library function used to print on the console. The library
functions are created by the designers of compilers.
All C standard library functions are defined inside the different header files saved
with the extension .h. We need to include these header files in our program to make use
of the library functions defined in such header files.
For example, To use the library functions such as printf/scanf we need to include
stdio.h in our program which is a header file that contains all the library functions
regarding standard input/output.
The list of mostly used header files is given in the following table.
Header
No Description
file
This is a standard input/output header file. It contains all the library
1 stdio.h
functions regarding standard input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(), puts(),etc.
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
This header file contains all the general library functions like
4 stdlib.h
malloc(), calloc(), exit(), etc.
This header file contains all the math operations related functions
5 math.h
like sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.
User defined function
A function may or may not accept any argument. It may or may not return any
value. Based on these facts, There are four different aspects of function calls.
1. Function without arguments and without return value.
2. Function without arguments and with return value.
3. Function with arguments and without return value.
4. Function with arguments and with return value.
Function without arguments and without return value
The functions without arguments are those which do not pass any arguments to
the called function and similarly the called also does not return any value to the calling
function. This is the simplest form of functions in C.
Example 1
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
#include<stdio.h>
void printName();
void main ()
{
printf("Hello World ");
printName();
}
void printName()
{
printf("C Programming");
}
Output
C Programming
Function with arguments and without return value
The functions with arguments passes the arguments to the called function but
does not return any value or result back to the calling function. This type of functions
performs better than the function without arguments and return value because we can
control the output by providing various values as arguments to the calling function.
Example
#include<stdio.h>
1. void sum(int, int);
2. void main()
3. {
4. int a,b,result;
5. printf("\nGoing to calculate the sum of two numbers:");
6. printf("\nEnter two numbers:");
7. scanf("%d %d",&a,&b);
8. sum(a,b);
9. }
10. void sum(int a, int b)
11. {
12. printf("\nThe sum is %d",a+b);
13. }
Output
Going to calculate the sum of two numbers:
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
Enter two numbers
10
24
The sum is 34
Function with arguments and with return value
The functions with arguments pass the arguments to the called function and
also waits for the results to be returned to the calling function. This type of functions
performs better than any other functions we can control the output by providing various
values as arguments to the calling function and also use the results returned for future
calculations.
Example
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers:
10
20
INTRODUCTION TO C PROGRAMMING( 22ESC145 )
MODULE 3 - FUNCTIONS
The sum is : 30
Function without arguments and with return value
The functions without arguments doesnot pass any arguments to the called
function and but waits for the results to be returned to the calling function. Examples for
this type of functions is getchar() which is declared in the library stdio.h.
Example
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers
10
24
The sum is 34