Understanding C Functions and Usage
Understanding C Functions and Usage
In c, we can divide a large program into the basic building blocks known as function. The function contains the
set of programming statements enclosed by { }. A function can be called multiple times to provide reusability
and modularity to the C program. In other words, we can say that the collection of functions creates a program.
Advantage of functions in C
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program.
We can track a large C program easily when it is divided into multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always a overhead in a C program.
Function declaration or prototype – This informs compiler about the function name, function parameters
and return value’s data type.
PARAMETERS
Parameters provide the data communication between the calling function and called function. There are two
types of parameters.
Actual Parameters-These are the parameters transferred from the calling program(main program) to the called
program.
Formal Parameters-These are the parameters transferred into the calling function(main program) from the called
program(function)
Example Program
#include<stdio.h>
// function declaration
int sum(int x, int y);
int main()
{
// function call
printf("sum = %d", sum(10, 10));
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
OUTPUT:
Enter some number for finding square
#include<stdio.h>
int i=10; -> Global Declaration
int main()
{
int j; ->Local Declaration
int fun(); // function declaration
printf("value of i in main : %d\n",i);
fun(); // function call
printf("value of function call : %d",i);
return 0;
}
int fun() // function definition
{
int k;
i=50;
return i;
}
Output
Value of i in main : 10
Value of function call : 50
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.
NOTE:
If the return data type of a function is “void”, then, it can’t return any values to the calling function.
If the return data type of the function is other than void such as “int, float, double etc”, then, it can return values
to the calling function.
C functions aspects syntax
function declaration:
int function ( int );
function call:
function ( a );
function definition:
1. With arguments and with return values
int function( int a )
{
statements;
return a;
}
function declaration:
void function ( int );
function call: function( a );
function definition:
2. With arguments and without return values
void function( int a )
{
statements;
}
function declaration:
void function();
function call: function();
3. Without arguments and without function definition:
return values void function()
{
statements;
}
function declaration:
int function ( );
function call: function ( );
function definition:
4. Without arguments and with
int function( )
return values
{
statements;
return a;
}
#include<stdio.h>
void sum();
void main()
{
printf("\n Calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Calculate the sum of two numbers:
Enter two numbers 10 24
The sum is 34
#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
#include<stdio.h>
void 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);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output
#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
The sum is : 30
C Library Functions
Library functions in C language are inbuilt functions which are grouped together and placed in a common place
called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined output instead of writing our own code to get
those outputs.
These library functions are created by the persons who designed and created C compilers.
All C standard library functions are declared in many header files which are saved as file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using “#include<file_name.h>” command to make use of
the functions those are declared in the header files.
When we include header files in our C program using “#include<filename.h>” command, all C code of the header
files are included in C program. Then, this C program is compiled by compiler and executed.
Check the below table to know all the C library functions and header files in which they are declared.
Click on the each header file name below to know the list of inbuilt functions declared inside them.
string.h All string related functions are defined in this header file
math.h All maths related functions are defined in this header file
time.h This header file contains time and clock related functions
ctype.h All character handling functions are defined in this header file
Call by value
Call by reference
1. CALL BY VALUE:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.
Note:
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \n and n = %d", m, n);
swap(m, n);
}
2. CALL BY REFERENCE:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both parameters.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
NOTE: A variable is not only associated with a data type, its value but also a storage class.
The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto
variables by default.
#include<stdio.h>
void increment(void);
void main()
{
increment();
increment();
increment();
increment();
}
void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
}
Output
0000
Static variables retain the value of the variable between different function calls.
The variables defined as static specifier can hold their value between the multiple function calls.
Static local variables are visible only to the function or the block in which they are defined.
A same static variable can be declared many times but can be assigned at only one time.
Default initial value of the static integral variable is 0 otherwise null.
10 11 12 13
The scope of this extern variable is throughout the main program. It is equivalent to global variable. Definition for
extern variable might be anywhere in the C program.
#include<stdio.h>
int x = 10 ;
int main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;
Output
The value of x is 10
The value of y is 50
4. EXAMPLE PROGRAM FOR REGISTER VARIABLE IN C:
Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in
main CPU memory.
Register variables will be accessed very faster than the normal variables since they are stored in register
memory rather than main memory.
But, only limited variables can be used as register since register size is very low.
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
return 0;
}
Output
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem.
Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion
involves several numbers of recursive calls.
#include <stdio.h>
int factorial(int);
int main()
{
int i = 5;
printf("Factorial of the number %d is %d\n", i, factorial(i));
return 0;
}
int factorial(int i)
{
if(i < 2)
{
return 1;
}
return i * factorial(i - 1);
}
Output
Factorial of the number 5 is 120
C PREPROCESSOR DIRECTIVES:
Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This
process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.
Preprocessor Syntax/Description
Syntax: #define
Macro
This macro defines constant value and can be any of the basic data types.
A program in C language involves into different processes. Below diagram will help you to understand all the processes
that a C program comes across.
KEY POINTS TO REMEMBER:
1. Source program is converted into executable code through different processes like precompilation, compilation,
assembling and linking.
2. Local variables uses stack memory.
3. Dynamic memory allocation functions use the heap memory.
#define – This macro defines constant value and can be any of the basic data types.
#include <file_name> – The source code of the file “file_name” is included in the main C program where
“#include <file_name>” is mentioned.
#include <stdio.h>
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
Output
“#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause statements are
included in source file.
Otherwise, “else” clause statements are included in source file for compilation and execution.
#include <stdio.h>
#define RAJA 100
int main()
{
#ifdef RAJA
printf("RAJA is defined. So, this line will be added in this C file\n");
#else
printf("RAJA is not defined\n");
#endif
return 0;
}
Output
RAJA is defined. So, this line will be added in this C file
Pragma is used to call a function before and after main function in a C program.
#include <stdio.h>
void function1( );
void function2( );
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
When a function gets number of arguments that changes at run time, we can go for variable length arguments.
It is denoted as … (3 dots)
stdarg.h header file should be included to make use of variable length argument functions.
#include <stdio.h>
#include <stdarg.h>
int main()
{
printf("The value from first function call = %d\n", add(2,2,3));
printf("The value from second function call= %d \n", add(4,2,3,4,5));
return 0;
}
va_start(valist, num);
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
va_end(valist);
return sum;
}
/*Note - In function add(2,2,3), first 2 is total number of arguments 2,3 are variable length arguments
In function add(4,2,3,4,5), 4 is total number of arguments 2,3,4,5 are variable length arguments
*/
Output
The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to
another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous
memory location. The purpose of pointer is to save memory space and achieve faster execution time.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer
used to dereference a pointer.
Syntax
data_type * pointer_variable_name;
Here,
data_type is the pointer's base type of C's variable types and indicates the type of the variable that
the pointer points to.
The asterisk (*: the same asterisk used for multiplication) which is indirection operator, declares a
pointer.
Example
#include <stdio.h>
int main()
return 0;
}
Output:
Example 2
#include <stdio.h>
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer
return 0;
}
Output
10
10
1191181796
1191181796
1191181800
1. While declaring/initializing the pointer variable, * indicates that the variable is a pointer.
2. The address of any variable is given by preceding the variable name with Ampersand &.
3. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is
going to contain an integer value. It means that a is going to contain the address of a variable
storing integer value.
4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can be
read as 'value at'.
Operator Meaning
* Serves 2 purpose
1. Declaration of a pointer
Types of Pointers in C
Null Pointer
We can create a null pointer by assigning null value during the pointer declaration. This method is useful
when you do not have any address assigned to the pointer. A null pointer always contains value 0.
#include <stdio.h>
int main()
return 0;
Output:
Void Pointer
In C programming, a void pointer is also called as a generic pointer. It does not have any standard data
type. A void pointer is created by using the keyword void. It can be used to store an address of any
variable.
Following program illustrates the use of a void pointer:
#include <stdio.h>
int main()
return 0;
Output:
In C, there are two equivalent ways to access and manipulate a variable content
#include <stdio.h>
int var = 1;
int *ptr;
ptr = &var;
*ptr=48;
return 0;}
Output
Pointer as a function parameter is used to hold addresses of arguments passed during function call. This is
also known as call by reference. When a function is called by reference any change made to the reference
variable will effect the original variable.
#include <stdio.h>
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
#include <stdio.h>
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
Output
92 is larger
Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as an argument in another
function. A pointer to a function is declared as follows,
Syntax: type (*pointer-name)(parameter);
Here is an example :
s (10, 20);
Example of Pointer to Function
#include <stdio.h>
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}
Output
Sum is 25
Syntax:
int **p1;
int main() {
int a = 10;
int *p1; //this can store the address of variable a
int **p2;
p1 = &a;
p2 = &p1;
return 0;
}
Output
Address of a = 2686724
Address of p1 = 2686728
Address of p2 = 2686732
Value at the address stored by p2 = 2686724
Value at the address stored by p1 = 10
Value of **p2 = 10
Here variable arr will give the base address, which is a constant pointer pointing to the first element of the
array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name
of the array and it acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
[NOTE: Now we can access every element of the array arr using p++ to move from one element to
another.]
Example program
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("\n%d", *p);
p++;
}
return 0;
}
Output
12345
Note
Then, the elements of the array are accessed using the pointer notation. By the way,
data[0] is equivalent to *data and &data[0] is equivalent to data
data[1] is equivalent to *(data + 1) and &data[1] is equivalent to data + 1
data[2] is equivalent to *(data + 2) and &data[2] is equivalent to data + 2
...
data[i] is equivalent to *(data + i) and &data[i] is equivalent to data + i
Pointer can also be used to create strings. Pointer variables of char type are treated as string.
Example program
#include <stdio.h>
int main()
{
char *str = "Hello welcome";
printf("%s",str);
return 0;
}
Output
Hello welcome
Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know
that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be
a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an
integer value. Following arithmetic operations are possible on the pointer in C language:
Increment
Decrement
Addition
Subtraction
Comparison
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by the size
of the data type to which the pointer is pointing.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 b
ytes.
return 0;
}
Output
Decrementing Pointer in C
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to the
previous location. The formula of decrementing the pointer is given below:
#include <stdio.h>
void main(){
int number=50;
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate previo
us location.
Output
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
#include<stdio.h>
int main(){
int number=50;
return 0;
Output
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e.,
4*3=12 increment. Since we are using 64-bit architecture, it increments 12. But if we were using 32-bit
architecture, it was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit
OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a
pointer will give an address. The formula of subtracting value from the pointer variable is given below:
Let's see the example of subtracting value from the pointer variable on 64-bit architecture.
#include<stdio.h>
int main(){
int number=50;
return 0;
Output
You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address value.
Multidimensional Array
In multidimensional array, the first array size does not have to be specified. The second (and any
subsequent) dimensions must be given.
Example
Now we know two dimensional array is array of one dimensional array. Hence let us see how to access a
two dimensional array through pointer.
int matrix[3][3];
Example Program 1
#include <stdio.h>
int main(void)
{
// 2d array
int aiData [3][3] = { { 9, 6, 1 }, { 14, 70, 50 }, {10, 12, 78} };
int *piData = NULL; //pointer to integer
int i,j;
piData = &aiData[0][0]; //You can also write *aiData
for (i = 0; i < 3; ++i) //Loop of row
{
for (j = 0; j < 3; ++j)// Loop for coloum
{
//Read element of 2D array
// *(piData + ( i * 3) + j) is equivalent to &matrix[i][j]
printf("aiData[%d][%d] = %d\n",i,j, *(piData + ( i * 3) + j));
}
}
return 0;
}
Output
aiData[0][0] = 9
aiData[0][1] = 6
aiData[0][2] = 1
aiData[1][0] = 14
aiData[1][1] = 70
aiData[1][2] = 50
aiData[2][0] = 10
aiData[2][1] = 12
aiData[2][2] = 78
Example Program 2
#include <stdio.h>
#define ROWS 3
#define COLS 3
/* Function declaration to input and print two dimensional array */
void inputMatrix(int matrix[][COLS], int rows, int cols);
void printMatrix(int matrix[][COLS], int rows, int cols);
int main()
{
int matrix[ROWS][COLS];
int i, j;
/* Input elements in matrix */
printf("Enter elements in %dx%d matrix.\n", ROWS, COLS);
inputMatrix(matrix, ROWS, COLS);
/* Print elements in matrix */
printf("Elements of %dx%d matrix.\n", ROWS, COLS);
printMatrix(matrix, ROWS, COLS);
return 0;
}
/**
* Function to take input in two dimensional array (matrix)
* from user.
*/
void inputMatrix(int matrix[][COLS], int rows, int cols)
{
int i, j;
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
// (*(matrix + i) + j is equivalent to &matrix[i][j]
scanf("%d", (*(matrix + i) + j));
}
}
}
void printMatrix(int (*matrix)[COLS], int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
// *(*(matrix + i) + j) is equivalent to matrix[i][j]
printf("%d ", *(*(matrix + i) + j));
}
printf("\n");
}
}
Output
Enter elements in 3x3 matrix.
123
456
789
Elements of 3x3 matrix.
123
456
789
Note: You can use any of the two notations int matrix[][COLS] or int (*matrix)[COLS], to access two
dimensional array using pointers. The first int matrix[][COLS] is general array notation. Whereas int
(*matrix)[COLS] is a pointer to array.
CUI GUI
(Programmer) (End user)
Programmer works with CUI.
Working of CUI
1. Open note pad & write a program
2. Open DOS & locate the compiler ->[Link]
3. Compile source program
4. Run program
Short cuts
Save-F2
Compile-Alt+F9
Run –Ctrl+F9
O/P-Alt+F5
How to pass argument in Command line
Cmd/> [Link] sample.c
->Generate [Link] file
Cmd/> [Link] 1 2 3 4
Example Program
#include <stdio.h>
if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc > 2 )
{
printf("\n Many values given by users.\n");
}
else
{
printf(" \n Single value expected.\n");
}
}
#include <stdio.h>
if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc > 2 )
{
printf("\n Many values given by users.\n");
}
else
{
printf(" \n Single value expected.\n");
}
}
Complicated declarations in C
Most of the times declarations are simple to read, but it is hard to read some declarations which involve
pointer to functions.
Rules:
Always read declarations from the inside out: Start from the innermost, if any, parenthesis.
Locate the identifier that's being declared, and start deciphering the declaration from there.
When there is a choice, always favor [] and () over *: If * precedes the identifier and [] follows it,
the identifier represents an array, not a pointer. Likewise, if * precedes the identifier and () follows
it, the identifier represents a function, not a pointer. (Parentheses can always be used to override the
normal priority of [] and () over *.)
Example 1:
int *a[10];
Applying rule:
void ( *(*f[]) () ) (); "f is an array of pointers to function returning pointer to function"
^^
void ( *(*f[]) () ) (); "f is an array of pointers to function returning pointer to function returning `void`"
^^^^