Unit 3
Function & Pointers
Similar to other languages C language also provides the facility of function. Function is the block of code which is used to perform a specific task. In c language the complete program is composed of function.
Functions are useful to divide c programs into smaller modules. Programmer can invoked these modules anywhere inside c program for any number of times.
Functions are used to increase readability of the code. Size of program can be reduce by using functions. By using function, programmer can divide complex tasks into smaller manageable tasks and test them independently before using them together.
Functions of C language are defined with the type of function. The type of functions indicates the data type of value which will return by function. In order to use function in the program, initially programmer have to inform compiler about the function. This is also called as defining a function.
In C programme all the function definition present outside the main function. All function need to be declared and defined before use. Function declaration requires function name, argument list, and return type.
Return Type Function name (Argument list)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
This is the default way of passing the parameters to the function. This is achieved by passing the copy of data to the function. This mechanism is also called as call by value. In case of parameter passing by value, the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function.
This mechanism is used when programmer don't want to change the value of passed parameters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables.
Pass-by-value is implemented by actual data transfer so additional storage is required to maintain the copies of passed parameters.
Example:
#include <stdio.h>
#include<conio.h>
/* function declaration goes here.*/
void swap( int p1, int p2 );
int main()
{
int a = 10;
int b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( a, b );
printf("After: Value of a = %d and value of b = %d\n", a, b );
getch();
}
void swap( int p1, int p2 )
{
int t;
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
Output :
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b (p2) = 10
After: Value of a = 10 and value of b = 20
Note: In the above example the values of “a” and “b” remain unchanged before calling swap function and after calling swap function.
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.
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 */
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
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
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.
The function called at program startup is named main . The main function can be defined with no parameters or with two parameters (for passing command-line arguments to a program when it begins executing). The two parameters are referred to here as argc and argv, though any names can be used because they are local to the function in which they are declared. A main function has the following syntax:
int main(void) { . . . }
int main(int argc, char *argv[ ]) { . . . })
argc
The number of arguments in the command line that invoked the program. The value of argc is nonnegative.
argv
Pointer to an array of character strings that contain the arguments, one per string. The value argv[argc] is a null pointer.
If the value of argc is greater than zero, the array members argv[0] through argv[argc –
1] inclusive contain pointers to strings, which are given implementation-defined values by the host environment before program startup. The intent is to supply the program with information determined before program startup from elsewhere in the host environment.
If the host environment cannot supply strings with letters in both uppercase and lowercase, the host environment ensures that the strings are received in lowercase.
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] is the null character if the program name is not available from the host environment.
If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc - 1] represent the program parameters.
The parameters argc and argv, and the strings pointed to by the argv array, can be modified by the program and keep their last-stored values between program startup and program termination.
In the main function definition, parameters are optional. However, only the parameters that are defined can be accessed.
A function which is predefined in c language is called library function. Library function is also called as built in function of C language. The definition of library function is stored in respective header file. Library functions are used to perform dedicated operation like taking input from user, displaying output, string handling operation, etc. Library functions are readily available and programmer can directly use it without writing any extra code. For example, printf () and scanf () are library function and their definition is stored in stdio header file.
The function called at program startup is named main . The main function can be defined with no parameters or with two parameters (for passing command-line arguments to a program when it begins executing). The two parameters are referred to here as argc and argv, though any names can be used because they are local to the function in which they are declared.
A main function has the following syntax:
int main(void) { . . . }
int main(int argc, char *argv[ ]) { . . . })
argc
The number of arguments in the command line that invoked the program. The value of argc is nonnegative.
argv
Pointer to an array of character strings that contain the arguments, one per string. The value argv[argc] is a null pointer.
If the value of argc is greater than zero, the array members argv[0] through argv[argc - 1] inclusive contain pointers to strings, which are given implementation-defined values by the host environment before program startup. The intent is to supply the program with information determined before program startup from elsewhere in the host environment.
If the host environment cannot supply strings with letters in both uppercase and lowercase, the host environment ensures that the strings are received in lowercase.
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] is the null character if the program name is not available from the host environment.
If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc –
1] represent the program parameters.
The parameters argc and argv, and the strings pointed to by the argv array, can be modified by the program and keep their last-stored values between program startup and program termination.
In the main function definition, parameters are optional. However, only the parameters that are defined can be accessed.
Call by value | Call by reference |
While calling a function we pass values of variables to it. Such functions are known as call by value. | While calling a function instead of passing the values of variables we pass the address of the variable. This is known as call by reference |
In this method the value of each variable in calling function is copied into corresponding dummy variables of the called function. | In this method the value of actual variable in the calling function are copied into dummy variables of the called function. |
With this method the changes made to the dummy variable in the called function have no effect on the values of actual variables in the calling function. | With this method using addresses we would have access to the actual variables and hence we would be able to manipulate them. |
The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. ... int n = 10; int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
One of the vital and heavily used feature ‘C’ is pointer. Most of the other programming languages also support pointers but only few of them use it freely. Support pointers but only few of them use it freely.
When we declare any variable in C language, there are three things associated with that variable.
1. Data type of variable: Data type defines the type of data that variable can hold. Data type tells compiler about the amount of memory allocate to the variable.
2. Address of Variable: Address of variable represent the exact address of memory location which is allocated to variable.
3. Value of variable : It is the value of variable which is store at the address of memory location allocated to variable.
Example : int n = 5;
In the above example ‘int’ is the data type which tells compiler to allocate 2 bytes of memory to variable ‘n’.
Once the variable is declare compiler allocated two bytes of memory to variable ‘n’. Suppose the address of that memory location is 1020. At the address of memory location 1020 the value 5 is store.
Memory map for above declaration is as follows.
use of &,/and ‘*’ operator
Consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,
printf (“Enter two numbers”);
scanf (“%d%d”, & a,&b);
c=a+b;
printf(“/n Addition is %d”, C);
printf(“/n Address of variable C is %d”, &C);
getch ();
}
Above program is the program for addition of two numbers in ‘C’ language. In the sevent instruction of above program we used operator ‘%’ and ‘&’ ‘%d’ is the access specifier which tells compiler to take integer value as a inpute whereas. ‘&a’ tells compile to store the taken value at the address of variable ‘a’.
In the ninth instruction compiler will print me value of ‘C’ so the output of 9th instruction is as follows.
Addition is 5 [Note : considering a = 2 and b = 3]
In the tenth instruction compiler will print me address of variable C.
So the output of lenth instruction is as follows. Address of variable C is 1020.
Now consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d %d”, & a, &b);
c=a+b;
printf(“\n Addition is %d”,C);
printf(“\n Address of variable C is %d”,&C);
printf(‘\n value of variable C is %d”, *(&C));
getch();
}
Now, we all are clear about the output of instruction 9 and 10.
In the 11th instruction, operator *and & is used. ‘*’ operator tells compile to pickup the value which is stored at the address of variable C. So the output of 11th instruction is as follow. Value of variable C is 5 [considering a = 24 b = 3;]
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.
Syntax : data_type *var_name;
Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
Example:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
POINTERS IN C
PROGRAM OUTPUT:
50
In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function.
In C, a callback function is a function that is called through a function pointer.
// A simple C program to demonstrate callback
#include<stdio.h>
void A()
{
printf("I am function A\n");
}
// callback function
void B(void (*ptr)())
{
(*ptr) (); // callback to A
}
int main()
{
void (*ptr)() = &A;
// calling function B and passing
// address of the function A as argument
B(ptr);
return 0;
}
I am function A
References:
The C Programming Language. 2nd Edition Book by Brian Kernighan and Dennis Ritchie
C Programming: A Modern Approach Book by Kim N. King
C Programming Absolute Beginner’s Guide book by S.D Perry