[go: up one dir, main page]

0% found this document useful (0 votes)
43 views14 pages

C6 C++ Note Unit 4

C++
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views14 pages

C6 C++ Note Unit 4

C++
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

C++ Functions

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

It makes the code optimized, we don't need to write much code.

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. return_type function_name(data_type parameter...)


2. {
3. //code to be executed
4. }

C++ Function Example


Let's see the simple example of C++ function.

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

Call by value and call by reference in C++


There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.

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:

Value of the data is: 3

Call by reference in C++


In call by reference, original value is modified because we pass reference (address).

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:

Value of x is: 100


Value of y is: 500

Difference between call by value and call by reference in


C++

No. Call by value Call by reference

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.

Let's see a simple example of recursion.

1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }

C++ Recursion Example


Let's see an example to print factorial number using recursion in C++ language.

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:

Enter any number: 5


Factorial of a number is: 120

We can understand the above program of recursive method call by the figure given below:

C++ Storage Classes


Storage class is used to define the lifetime and visibility of a variable and/or function within a
C++ program.

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

Storage Class Keyword Lifetime Visibility Initial Value

Automatic auto Function Block Local Garbage

Register register Function Block Local Garbage

Mutable mutable Class Local Garbage

External extern Whole Program Global Zero

Static static Whole Program Local Zero

Automatic Storage Class


It is the default storage class for all local variables. The auto keyword is applied to all local
variables automatically.

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.

Register Storage Class


The register variable allocates memory in register than RAM. Its size is same of register size. It
has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.


1. register int counter=0;

Static Storage Class


The static variable is initialized only once and exists till the end of a program. It retains its value
between multiple functions call.

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

External Storage Class


The extern variable is visible to all the programs. It is used if two or more files are sharing same
variable or function.

1. extern int counter=0;


Memory Management?
Memory management is a process of managing computer memory, assigning the memory space
to the programs to improve the overall system performance.

Why is memory management required?


As we know that arrays store the homogeneous data, so most of the time, memory is allocated to
the array at the declaration time. Sometimes the situation arises when the exact memory is not
determined until runtime. To avoid such a situation, we declare an array with a maximum size,
but some memory will be unused. To avoid the wastage of memory, we use the new operator to
allocate the memory dynamically at the run time.

Memory Management Operators


In C language, we use the malloc() or calloc() functions to allocate the memory dynamically at
run time, and free() function is used to deallocate the dynamically allocated memory. C++ also
supports these functions, but C++ also defines unary operators such as new and delete to
perform the same tasks, i.e., allocating and freeing the memory.

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

1. pointer_variable = new data-type

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;

In the above example, 'p' is a pointer of type int.

Example 2:
1. float *q;
2. q = new float;

In the above example, 'q' is a pointer of type float.

In the above case, the declaration of pointers and their assignments are done separately. We can
also combine these two statements as follows:

1. int *p = new int;


2. float *q = new float;

Assigning a value to the newly created object


Two ways of assigning values to the newly created object:

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:

1. pointer_variable = new data-type(value);

Let's look at some examples.

1. int *p = new int(45);


2. float *p = new float(9.8);

How to create a single dimensional array


As we know that new operator is used to create memory space for any data-type or even user-
defined data type such as an array, structures, unions, etc., so the syntax for creating a one-
dimensional array is given below:

1. pointer-variable = new data-type[size];


Examples:
1. int *a1 = new int[8];

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:

1. delete [size] pointer_variable;

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;

Let's understand through a simple example:

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.

You might also like