C function
[Link] is C function?
[Link] of C functions
3.C function declaration, function call and definition with example program
[Link] to call C functions in a program?
1. Call by value
2. Call by reference
5.C function arguments and return values
1. C function with arguments and with return value
2. C function with arguments and without return value
3. C function without arguments and without return value
4. C function without arguments and with return value
[Link] of C functions
1. Library functions in C
2. User defined functions in C
[Link]/Adding user defined function in C library
[Link] line arguments in C
[Link] length arguments in C
C functions are basic building blocks in a program. All C programs are written
using functions to improve re-usability, understand ability and to keep track on
them. You can learn below concepts of C functions in this section in detail.
WHAT IS C FUNCTION?
A large C program is divided into basic building blocks called C function.
C function contains set of instructions enclosed by “{ }” which performs
specific operation in a C program. Actually, Collection of these functions creates a
C program.
2. USES OF C FUNCTIONS:
•C functions are used to avoid rewriting same logic/code again and
again in a program.
•There is no limit in calling C functions to make use of same
functionality wherever required.
•We can call functions any number of times in a program and from any
place in a program.
•A large C program can easily be tracked when it is divided into
functions.
•The core concept of C functions are, re-usability, dividing a big task
into small pieces to achieve the functionality and to improve
3. C FUNCTION DECLARATION, FUNCTION CALL AND FUNCTION DEFINITION:
There are 3 aspects in each C function. They are,
•Function declaration or prototype – This informs compiler about the function name, function
parameters and return value’s data type.
•Function call – This calls the actual function
•Function definition – This contains all the statements to be executed.
C functions aspects syntax
function definition Return_type function_name (arguments list)
{ Body of function; }
function call function_name (arguments list);
function declaration return_type function_name (argument list);
SIMPLE EXAMPLE #include<stdio.h>
PROGRAM FOR C // function prototype, also called function
FUNCTION: declaration
•As you know, functions float square ( float x );
should be declared and // main function, program starts from here
defined before calling in a C
program. int main( )
{
•In the below program, float m, n ;
function “square” is called printf ( "\nEnter some number for finding
from main function. square \n");
scanf ( "%f", &m ) ;
•The value of “m” is passed as // function call
argument to the function n = square ( m ) ;
“square”. This value is printf ( "\nSquare of the given number %f is
multiplied by itself in this %f",m,n );
function and multiplied value }
“p” is returned to main
function from function float square ( float x ) // function definition
“square”. {
float p ;
p = x *square
Enter some number for finding x;
2 return ( p ) ;
}
Square of the given number 2.000000 is 4.000000
Recall the parameters
Call by value
Call by Reference
4. HOW TO CALL C FUNCTIONS IN A PROGRAM?
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. 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:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY
VALUE):
#include<stdio.h>
// function prototype, also called function
declaration
•In this program, the values void swap(int a, int b);
of the variables “m” and “n”
are passed to the function int main()
“swap”. {
int m = 22, n = 44;
// calling swap function by value
•These values are copied to
printf(" values before swap m = %d \nand n =
formal parameters “a” and %d", m, n);
“b” in swap function and swap(m, n);
used. }
Output: void swap(int a, int b)
values before swap m = {
22 int tmp;
and n = 44 tmp = a;
values after swap m = 44 a = b;
and n = 22 b = tmp;
printf(" \nvalues after swap m = %d\n and n =
%d", a, b);
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>
EXAMPLE PROGRAM FOR C // function prototype, also called function declaration
FUNCTION (USING CALL BY void swap(int *a, int *b);
REFERENCE):
•In this program, the address of int main()
the variables “m” and “n” are {
passed to the function “swap”. int m = 22, n = 44;
// calling swap function by reference
•These values are not copied to
printf("values before swap m = %d \n and n = %d",m,n);
formal parameters “a” and “b” in swap(&m, &n);
swap function. }
•Because, they are just holding
the address of those variables. void swap(int *a, int *b)
•This address is used to access {
and change the values of the int tmp;
tmp = *a;
variables.
Output: *a = *b;
values before swap m = 22 *b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
and n = 44
}
values after swap a = 44
and b = 22
All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example
C programs for each one of the below.
1.C function with arguments (parameters) and with return value.
2.C function with arguments (parameters) and without return value.
3.C function without arguments (parameters) and without return value.
4.C function without arguments (parameters) and with return value.
C functions aspects syntax
function declaration:
int function ( int );
function call: function ( a );
1. With arguments and with function definition:
return values int function( int a )
{
statements;
return a;
}
function declaration:
void function ( int );
function call: function( a );
2. With arguments and without function definition:
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;
}
1. EXAMPLE PROGRAM FOR WITH ARGUMENTS & #include<stdio.h>
WITH RETURN VALUE: #include<string.h>
In this program, integer, array and string are passed int function(int, int[], char[]);
as arguments to the function. The return type of this
function is “int” and value of the variable “a” is int main()
returned from the function. The values for array and {
string are modified inside the function itself. int i, a = 20;
int arr[5] = {10,20,30,40,50};
printf("value of str is %s\n",str); char str[30] = "\"fresh2refresh\"";
printf("\n ***values after modification***\n");
a= function(a, &arr[0], &str[0]); printf(" ***values before
printf("value of a is %d\n",a); modification***\n");
for (i=0;i<5;i++) printf("value of a is %d\n",a);
{
// Accessing each variable for (i=0;i<5;i++)
printf("value of arr[%d] is %d\n",i,arr[i]); {
} // Accessing each variable
printf("value of str is %s\n",str); printf("value of arr[%d] is %d\
return 0; n",i,arr[i]);
} }
int function(int a, int *arr, char *str)
{
int i;
a = a+20;
arr[0] = arr[0]+50;
arr[1] = arr[1]+50;
arr[2] = arr[2]+50;
arr[3] = arr[3]+50; value of a is 20
arr[4] = arr[4]+50; value of arr[0] is 10
strcpy(str,"\"modified string\""); value of arr[1] is 20
value of arr[2] is 30
return a; value of arr[3] is 40
value of arr[4] is 50
} value of str is “fresh2refresh”***values after
modification***
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100
value of str is “modified string”
#include<stdio.h>
2. EXAMPLE PROGRAM FOR
void function(int, int[], char[]);
WITH ARGUMENTS &
WITHOUT RETURN VALUE:
int main()
In this program, integer, array
{
and string are passed as
int a = 20;
arguments to the function.
int arr[5] = {10,20,30,40,50};
The return type of this
char str[30] = "\"fresh2refresh\"";
function is “void” and no
values can be returned from
function(a, &arr[0], &str[0]);
the function. All the values of
return 0;
integer, array and string are
}
manipulated and displayed
void function(int a, int *arr, char *str)
inside the function itself.
{
value of a is 20 int i;
printf("value of a is %d\n\n",a);
value of arr[0] is 10 for (i=0;i<5;i++)
value of arr[1] is 20 {
value of arr[2] is 30 // Accessing each variable
value of arr[3] is 40 printf("value of arr[%d] is %d\n",i,arr[i]);
value of arr[4] is 50 }
printf("\nvalue of str is %s\n",str);
value of str is “fresh2refresh” }
3. EXAMPLE PROGRAM FOR
WITHOUT ARGUMENTS & #include<stdio.h>
WITHOUT RETURN VALUE: void test();
In this program, no values are
passed to the function “test” int main()
and no values are returned {
from this function to main test();
function. return 0;
}
void test()
{
int a = 50, b = 80;
printf("\nvalues : a = %d and b = %d", a, b);
}
values : a = 50 and b = 80
4. EXAMPLE PROGRAM FOR WITHOUT #include<stdio.h>
ARGUMENTS & WITH RETURN VALUE:
In this program, no arguments are passed to the int sum();
function “sum”. But, values are returned from this
function to main function. Values of the variable a int main()
and b are summed up in the function “sum” and {
the sum of these value is returned to the main int addition;
function. addition = sum();
printf("\nSum of two given values = %d",
addition);
return 0;
}
int sum()
{
int a = 50, b = 80, sum;
sum = a + b;
return sum;
}
Sum of two given values = 130
SCOPE RULES
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:
1. Inside a function or a block which is called local variables,
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which are called formal parameters.
#include int main ()
Local Variables
{
Variables that are declared inside a /* local variable declaration */
function or block are called local
int a, b; int c;
variables. They can be used only by
statements that are inside that /* actual initialization */
function or block of code. Local a = 10; b = 20;
variables are not known to functions c = a + b;
outside their own. The following printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
example shows how local variables return 0;
are used. Here all the variables a, b, }
and c are local to main() function.
Global Variables #include<stdio.h>
/* global variable declaration */
Global variables are defined outside a
int g;
function, usually on top of the program. int main ()
Global variables hold their values {
throughout the lifetime of your program /* local variable declaration */
and they can be accessed inside any of int a, b;
the functions defined for the program. A /* actual initialization */
global variable can be accessed by any
a = 10; b = 20; g = a + b;
printf ("value of a = %d, b = %d and g = %d\n",
function. That is, a global variable is
a, b, g);
available for use throughout your entire
return 0;
program after its declaration. The }
following program shows how global
variables are used in a program.
OUTPUT : value of g = 10
#include<stdio.h>
Formal Parameters
/* global variable declaration */
int a = 20;
Formal parameters are
int main ()
treated as local variables
{
with-in a function and
/* local variable declaration in main function */
they take precedence
int a = 10; int b = 20; int c = 0;
over global variables.
printf ("value of a in main() = %d\n", a);
Following is an example:
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;
}
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 Data Type Initial Default Value
int 0
When a local variable is defined, it char '\0'
is not initialized by the system, you float 0
must initialize it yourself. double 0
pointer NULL
Global variables are initialized
automatically by the system when
you define them, as follows:
Passing Arrays to Functions Way-1 Formal parameters as a pointer:
Formal parameters as a pointer:
If you want to pass a single- void myFunction(int *param)
dimension array as an {
argument in a function, you .
would have to declare a .
formal parameter in one of .
following three ways and all }
three declaration methods
produce similar results
because each tells the Way-2 Formal parameters as a sized array:
compiler that an integer void myFunction(int param[]) { . . . }
pointer is going to be
received. Similarly, you can void myFunction(int param[10])
pass multi-dimensional {
arrays as formal .
parameters. .
Way-3 .
Formal parameters as an unsized array:
}
void myFunction(int param[])
{
.
.
}
Example consider the following function, which takes an array as an argument along with another argument and
based on the passed arguments, it returns the average of the numbers passed through the array as follows:
double getAverage(int arr[], int size) let us call the above function as follows:
{ #include <stdio.h>
int i; double avg; double sum; /* function declaration */
for (i = 0; i < size; ++i) double getAverage(int arr[], int size);
{ int main ()
sum += arr[i]; {
} /* an int array with 5 elements */
avg = sum / size; int balance[5] = {1000, 2, 3, 17, 50};
return avg; double avg;
} /* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg ); return 0;
}
OUTPUT : Average value is: 214.400000
Return Array from a Function
C programming does not allow to return an entire array as an argument to a function.
However, you can return a pointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a function returning a
pointer as in the following example:
int * myFunction()
{
.
.
.
}
Second point to remember is that C does not advocate to return the address of a local variable to outside of the
function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an array and
call this function as follows:
#include <stdio.h>
/* function to generate and return random numbers */
int * getRandom( )
{
int main ()
static int r[10]; int i; {
/* set the seed */ /* a pointer to an int */
srand( (unsigned)time( NULL ) ); int *p; int i; p = getRandom();
for ( i = 0; i < 10; ++i) for ( i = 0; i < 10; i++ )
{
r[i] = rand();
{
printf( "r[%d] = %d\n", i, r[i]); printf( "*(p + %d) : %d\n", i, *(p + i));
} }
return r; return 0;
} }
/* main function to call above defined function */
OUTPUT :
r[0] = 313959809
r[1] = 1759055877
r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
r[5] = 167288147
r[6] = 1827471542
r[7] = 834791014
r[8] = 1901409888
r[9] = 1990469526
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
*(p + 5) : 167288147
*(p + 6) : 1827471542
*(p + 7) : 834791014
Pointer to an Array
It is most likely that you would not understand this section until you are through with the chapter ‘Pointers’. Assuming you
have some understanding of pointers in C, let us start: An array name is a constant pointer to the first element of the array.
Therefore, in the declaration:
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following
program fragment assigns p as the address of the first element of balance:
double *p;
double balance[10];
p = balance;
POINTERS
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and
other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes
necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps. As
you know, every variable is a memory location and every memory location has its address defined which can be
accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example,
which prints the address of the variables defined:
#include int main ()
{
int var1; char var2[10];
printf("Address of var1 variable: %x\n", &var1 ); printf("Address
of var2 variable: %x\n", &var2 );
return 0;
}
OUTPUT:
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
Like any variable or constant, you must declare a pointer before using it to store any variable address. The general
form of a pointer variable declaration is:
type *var-name;
type is the pointer's base type; it must be a valid C data type and varname is the name of the pointer variable.
The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement, the
asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long
hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the variable or constant that the
pointer points to.
How to Use Pointers?
There are a few important operations, which we will do with the help of pointers very frequently.
(a) We define a pointer variable,
(b) (b) assign the address of a variable to a pointer, and
(c) (c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
The following example makes use of these operations:
#include <stdio.h>
int main ()
{ OUTPUT:
int var = 20; Address of var variable: bffd8b3c
/* actual variable declaration */ Address stored in ip variable: bffd8b3c
int *ip; /* pointer variable declaration */ Value of *ip variable: 20
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be
assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
OUTPUT: The value of ptr is 0
Pointers in Detail
Pointers have many but easy concepts and they are very important to C programming.
The following important pointer concepts should be clear to any C programmer:
Concept Description
Pointer arithmetic There are four arithmetic operators that can be used in pointers: ++, --, +, -
Array of pointers You can define arrays to hold a number of pointers.
Pointer to pointer C allows you to have pointer on a pointer and so on.
Passing pointers to functions in C Passing an argument by reference or by address enable the passed argument
to be changed in the calling function by the called function.
Return pointer from functions in C C allows a function to return a pointer to the local variable, static variable, and
dynamically allocated memory as well.
Pointer Arithmetic
A pointer in C is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer
just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and –
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000.
Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer:
Array of Pointers
Before we understand the concept of arrays of pointers, let us consider the following example, which uses an array of 3
integers:
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, var[i] );
}
OUTPUT:
return 0;
Value of var[0] = 10
} Value of var[1] = 100
Value of var[2] = 200
Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a
variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to
the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of
its name. For example, the following declaration declares a pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk
operator be applied twice, as is shown below in the example:
OUTPUT : Value of var = 3000
#include <stdio.h> Value available at *ptr = 3000
int main () Value available at **pptr = 3000
{
int var; int *ptr; int **pptr; var = 3000; /* take the address of var */
ptr = &var; /* take the address of ptr using address of operator & */
pptr = &ptr; /* take the value using pptr */
printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr); return 0; }
Passing Pointers to Functions
C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer
type. Following is a simple example where we pass an unsigned long pointer to a function and change the value inside
the function which reflects back in the calling function:
#include<stdio.h>
#include <conio.h>
void getSeconds(unsigned long *par);
int main ()
{
unsigned long sec;
getSeconds( &sec );
/* print the actual value */
printf("Number of seconds: %ld\n", sec );
return 0;
}
void getSeconds(unsigned long *par)
{
/* get the current number of seconds */
*par = time( NULL );
return; OUTPUT : Number of seconds :1294450468
}
C supports a wide range of functions that manipulate null-terminated strings: