C6 C++ Note Unit 4
C6 C++ Note Unit 4
The function in C++ language is also known as procedure or subroutine in other programming
languages.
To perform any task, we can create function. A function can be called many times. It provides
modularity and code reusability.
Advantage of functions in C
There are many advantages of functions.
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the same
code again and again.
2) Code optimization
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is repetition
of code.
But if you use functions, you need to write the logic only once and you can reuse it several times.
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
ceil(x), cos(x), exp(x), 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 complexity of a big program and optimizes the code.
Declaration of a function
The syntax of creating function in C++ language is given below:
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
Let's understand call by value and call by reference in C++ language one by one.
Call by value in C++
In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the function parameter in
stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Let's try to understand the concept of call by value in C++ language by the example given below:
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Output:
Here, address of the value is passed in the function, so actual and formal arguments share the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.
Let's try to understand the concept of call by reference in C++ language by the example given
below:
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
1 A copy of value is passed to the function An address of value is passed to the function
2 Changes made inside the function is not reflected Changes made inside the function is reflected
on other functions outside the function also
3 Actual and formal arguments will be created in Actual and formal arguments will be created in
different memory location same memory location
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The function
which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is known as tail
recursion. In tail recursion, we generally call the same function with return statement.
1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int factorial(int);
6. int fact,value;
7. cout<<"Enter any number: ";
8. cin>>value;
9. fact=factorial(value);
10. cout<<"Factorial of a number is: "<<fact<<endl;
11. return 0;
12. }
13. int factorial(int n)
14. {
15. if(n<0)
16. return(-1); /*Wrong value*/
17. if(n==0)
18. return(1); /*Terminating condition*/
19. else
20. {
21. return(n*factorial(n-1));
22. }
23. }
Output:
We can understand the above program of recursive method call by the figure given below:
Lifetime refers to the period during which the variable remains active and visibility refers to the
module of a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
1. Automatic
2. Register
3. Static
4. External
5. Mutable
1. {
2. auto int y;
3. float y = 3.45;
4. }
The above example defines two variables with a same storage class, auto can only be used within
functions.
It is recommended to use register variable only for quick access such as in counter.
The static variable has the default value 0 which is provided by compiler.
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
New operator
A new operator is used to create the object while a delete operator is used to delete the object.
When the object is created by using the new operator, then the object will exist until we
explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of
the object is not related to the block structure of the program.
Syntax
The above syntax is used to create the object using the new operator. In the above
syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the operator, and 'data-
type' defines the type of the data.
Example 1:
1. int *p;
2. p = new int;
Example 2:
1. float *q;
2. q = new float;
In the above case, the declaration of pointers and their assignments are done separately. We can
also combine these two statements as follows:
o We can assign the value to the newly created object by simply using the assignment operator. In
the above case, we have created two pointers 'p' and 'q' of type int and float, respectively. Now,
we assign the values as follows:
1. *p = 45;
2. *q = 9.8;
We assign 45 to the newly created int object and 9.8 to the newly created float object.
o We can also assign the values by using new operator which can be done as follows:
In the above statement, we have created an array of type int having a size equal to 8 where p[0]
refers first element, p[1] refers the first element, and so on.
Delete operator
When memory is no longer required, then it needs to be deallocated so that the memory can be
used for another purpose. This can be achieved by using the delete operator, as shown below:
1. delete pointer_variable;
In the above statement, 'delete' is the operator used to delete the existing object,
and 'pointer_variable' is the name of the pointer variable.
In the previous case, we have created two pointers 'p' and 'q' by using the new operator, and can
be deleted by using the following statements:
1. delete p;
2. delete q;
The dynamically allocated array can also be removed from the memory space by using the
following syntax:
In the above statement, we need to specify the size that defines the number of elements that are
required to be freed. The drawback of this syntax is that we need to remember the size of the
array. But, in recent versions of C++, we do not need to mention the size as follows:
1. delete [ ] pointer_variable;
1. #include <iostream>
2. using namespace std
3. int main()
4. {
5. int size; // variable declaration
6. int *arr = new int[size]; // creating an array
7. cout<<"Enter the size of the array : ";
8. std::cin >> size; //
9. cout<<"\nEnter the element : ";
10. for(int i=0;i<size;i++) // for loop
11. {
12. cin>>arr[i];
13. }
14. cout<<"\nThe elements that you have entered are :";
15. for(int i=0;i<size;i++) // for loop
16. {
17. cout<<arr[i]<<",";
18. }
19. delete arr; // deleting an existing array.
20. return 0;
21. }
In the above code, we have created an array using the new operator. The above program will take
the user input for the size of an array at the run time. When the program completes all the
operations, then it deletes the object by using the statement delete arr.
Output
Advantages of the new operator
The following are the advantages of the new operator over malloc() function:
o It does not use the sizeof() operator as it automatically computes the size of the data object.
o It automatically returns the correct data type pointer, so it does not need to use the typecasting.
o Like other operators, the new and delete operator can also be overloaded.
o It also allows you to initialize the data object while creating the memory space for the object.