Unit III
Functions and Pointers
1 Explain built in user define function
User defined functions are the functions defined by the programmer or user.
C++ provides the facility to user to define their own functions.
When the function gets call anywhere from program the function body gets execute.
Structure
#include<iostream>
Void function_name(){
}
Int main(){
Function_name();
}
Example
#include<iostream>
Using namespace std;
Int add(int, int);
Int main(){
int a, b, sum;
cout<<"Enters two numbers ";
cin >> a >> b;
sum = add(a, b);
cout << "Sum = " << sum;
return 0;
}
Int add(int a, int b)
{
int add;
add = a + b;
return add; }
}
2 What is function definition and declaration?
Function is declared globally to inform the compiler about function name, function parameters and return type.
Return_type function_name([arguments type)];
Example
Void create_function(){
}
Function call
Function call has parameter list with function name. Using function call function can be called anywhere in program.
Function_name([actual arguments]);
Example
Void createfunction() {
cout << "Function created";
}
int main() {
createfunction();
return 0;
}
Function definition.
Function definition consists of block of statements which contains actual execution code. When function gets called in program control comes to the function definition.
Return_type function_name([arguments])
{
Statements;
}
Example
Int main() {
createfunction();
return 0;
}
void createfunction() {
cout <<”Functoin created.”;
}
Void mycreateunction();
int main() {
createfunction();
return 0;
}
void createfunction() {
cout << “Function created”;
}
3 What is pass by value and pass by reference in function explain with examples?
Function arguments in c programming
Basically, there are two types of arguments:
- Actual arguments
- Formal arguments
The variables declared in the function prototype or definition are known as Formal arguments and the values that are passed to the called function from the main function are known as Actual arguments.
The actual arguments and formal arguments must match in number, type, and order.
Following are the two ways to pass arguments to the function:
- Pass by value
- Pass by reference
Pass by Value
Pass by value is a method in which a copy of the value of the variables is passed to the function for the specific operation.
In this method, the arguments in the function call are not modified by the change in parameters of the called function. So the original variables remain unchanged.
Example of passing arguments by value to function in C
// arguments pass by value
# include <stdio.h>
Int add (int a, int b)
{
return( a + b );
}
Int main()
{
int x, y, z;
x = 5;
y = 5;
z = add(x,y); // call by value
Return 0;
}
//end of program
In this program, function add() is called by passing the arguments x and y.
The copy of the values of x and y are passed to a and b respectively and then are used in the function.
So by changing the values of a and b, there will be no change in the actual arguments x and y in the function call.
Pass by reference
Pass by reference is a method in which rather than passing direct value the address of the variable is passed as an argument to the called function.
When we pass arguments by reference, the formal arguments in the called function becomes the assumed name or aliases of the actual arguments in the calling function. So the function works on the actual data.
Example of passing arguments by reference to function in C
// arguments pass by reference
#include <stdio.h>
Void swap (int *a, int *b) // a and b are reference variables
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Int main()
{
int x = 2, y = 4;
printf("before swapping x = %d and y = %d\n", x, y);
swap(&x, &y); // call by reference
return 0;
} //end of program
In the above program, the formal arguments a and b becomes the alias of actual arguments x and y when the function was called.
So when the variables a and b are interchanged x and y are also interchanged. So the output becomes like this.
Output
Before swapping x = 2 and y = 4
After swapping x = 4 and y = 2
Now, if the function was defined as:
Void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
This is the pass by value method so here even if the values are swapped in the function the actual value won’t interchange and output would become like this:
Before swapping x = 2 and y = 4
After swapping x = 4 and y = 2
4 What is calling by value explain with examples?
Call by value in C
- In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.
- In call by value method, we can not modify the value of the actual parameter by the formal parameter.
- In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.
- The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
- #include<stdio.h>
- Void change(int num) {
- Printf("Before adding value inside function num=%d \n",num);
- Num=num+100;
- Printf("After adding value inside function num=%d \n", num);
- }
- Int main() {
- Int x=100;
- Printf("Before function call x=%d \n", x);
- Change(x);//passing value in function
- Printf("After function call x=%d \n", x);
- Return 0;
- }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by Value Example: Swapping the values of the two variables
- #include <stdio.h>
- Void swap(int , int); //prototype of the function
- Int main()
- {
- Int a = 10;
- Int b = 20;
- Printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
- Swap(a,b);
- Printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20
- }
- Void swap (int a, int b)
- {
- Int temp;
- Temp = a;
- a=b;
- b=temp;
- Printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10
- }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
5 What is call by reference explain with examples?
Call by reference in C
- In call by reference, the address of the variable is passed into the function call as the actual parameter.
- The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.
- In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.
Consider the following example for the call by reference.
- #include<stdio.h>
- Void change(int *num) {
- Printf("Before adding value inside function num=%d \n",*num);
- (*num) += 100;
- Printf("After adding value inside function num=%d \n", *num);
- }
- Int main() {
- Int x=100;
- Printf("Before function call x=%d \n", x);
- Change(&x);//passing reference in function
- Printf("After function call x=%d \n", x);
- Return 0;
- }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
- #include <stdio.h>
- Void swap(int *, int *); //prototype of the function
- Int main()
- {
- Int a = 10;
- Int b = 20;
- Printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
- Swap(&a,&b);
- Printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20
- }
- Void swap (int *a, int *b)
- {
- Int temp;
- Temp = *a;
- *a=*b;
- *b=temp;
- Printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10
- }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
6 What is pointer variable give example?
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.
Pointer 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;
}
1
2
3
4
5
6
7
8
9
10
11
7 Write a program for addition of two numbers.
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 seventh instruction of above program we used operator ‘%’ and ‘&’ ‘%d’ is the access specifier which tells compiler to take integer value as a input 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 length instruction is as follows. Address of variable C is 1020.
8 What is Pointer Arithmetic?
Pointer arithmetic is slightly different from arithmetic we normally use in our daily life. The only valid arithmetic operations applicable on pointers are:
- Addition of integer to a pointer
- Subtraction of integer to a pointer
- Subtracting two pointers of the same type
The pointer arithmetic is performed relative to the base type of the pointer. For example, if we have an integer pointer ip which contains address 1000, then on incrementing it by 1, we will get 1004 (i.e 1000 + 1 * 4) instead of 1001 because the
Size of the int data type is 4 bytes. If we had been using a system where the size of int is 2 bytes then we would get 1002 ( i.e 1000 + 1 * 2 ).
Similarly, on decrementing it we will get 996 (i.e 1000 - 1 * 4) instead of 999.
So, the expression ip + 4 will point to the address 1016 (i.e 1000 + 4 * 4 ).
Let's take some more examples.
1 2 3 | Int i = 12, *ip = &i; Double d = 2.3, *dp = &d; Char ch = 'a', *cp = &ch;
|
Suppose the address of i, d and ch are 1000, 2000, 3000 respectively, therefore ip, dp and cp are at 1000, 2000, 3000 initially.
9 Explain Passing parameters by reference
A Parameter is the symbolic name for "data" that goes into a function. There are two ways to pass parameters in C: Pass by Value, Pass by Reference.
Pass by Value
Pass by Value, means that a copy of the data is made and stored by way of the name of the parameter. Any changes to the parameter have NO affect on data in the calling function.
Pass by Reference
A reference parameter "refers" to the original data in the calling function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL variable.
There are two ways to make a pass by reference parameter:
ARRAYS
Arrays are always pass by reference in C. Any change made to the parameter containing the array will change the value of the original array.
The ampersand used in the function prototype.
Function ( & parameter_name )
To make a normal parameter into a pass by reference parameter, we use the "& param" notation. The ampersand (&) is the syntax to tell C that any changes made to the parameter also modify the original variable containing the data.
10 Explain pointer to pointer with example
Till this point we are clear about the pointer of different data types in this section we study the pointer of pointer which is also called as double pointer.
Pointer variable is responsible to hold the address of a variable but when user defines pointer to pointer variable then that variable is responsible to hold the address of pointer variable. Pointer to pointer variable is declare by putting extra asterisk sign before the pointer variable. Following is the declaration of pointer to pointer variable
Data-Type**variable-name
Data type is responsible to define type of value stored at the location of pointer variable.
Two asterisk signs indicated that it is pointer to pointer variable.
User can allocate any name to the pointer variable by following all the rules of allocating variable name.
Consider the following program
#include<stdio.h>
#include<conio.h>
Void main()
{
Int n=5;
Int *np,**npp;
Np=&n;
Npp=&np;
Printf("\n value of n is %d",n);
Printf("\n value of n is %d",*np);
Printf("\n value of n is %d",**npp);
Getch();
}
Above program is basic program for double pointer which contains three ‘printf’ statements. The explanation of these statements are as follows.
1.In the first ‘printf’ statement compiler will directly print the value of variable ‘n’ which is ‘5’.
2.In the second ‘printf’ statement compiler will print the value of pointer variable ‘np’. ‘np’ variable contains the address of variable ‘n’ but as we put the asterisk sign before it so it will print the value which is present at the address of variable ‘n’ which is ‘5’
3.In the third printf statement compiler will print the value of pointer to pointer variable ‘npp’. ‘npp’ variable contains the address of pointer variable ‘np’ and ‘np’ variable contains the address of variable n’ but as we put the two asterisk signs before it so it will print the value which is present at the address of variable ‘n’ which is ‘5’. If we put only one asterisk sign the it will print the address of variable ‘n’.
User can allocate any name to the pointer variable by following all the rules of allocating variable