Category: CPlusPlus Tutorial

  • C++ Pointers and Arrays

    In this section, you will learn how pointers and arrays are related to each other. Before that, you should have knowledge on the following topics in C.

    Pointers and arrays are strongly related to each other. In general, the name of the array is a pointer itself, it points to the address of the first element in an array. For example, if an array of name score[] is created then the name (score) contains the address of a first element. Through this, we can access other elements.

    Consider the following:

    double *ptr;		
    double arr[10];
    
    ptr = arr;

    In the above example, the variable arr will provide the base address, which is a constant pointer pointing to the first element of the array that is to arr[0]. And hence the arr will contain the address of arr[0]. Thus, the above program fragment assigns ptr with the address of the arr.

    Once the address of the first element is stored in the pointer ‘p’, we can access other elements of array elements using *p, *(p+1), *(p+2), and so on.

    Let us see it in a C++ program.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int *ptr;
       int arr[] = { 10, 20, 30, 40, 50 };
    
       //assigning the address of first element to pointer
       ptr = arr;
    
       for (int i = 0; i < 5; i++)
       {
          cout << "Address: " << ptr << endl;
          cout << "Value: " << *ptr << endl;
          ptr++;
       }
    
       return 0;
    }

    Output:

    Address: 0x7ffea05a98f0
    Value: 10
    Address: 0x7ffea05a98f4
    Value: 20
    Address: 0x7ffea05a98f8
    Value: 30
    Address: 0x7ffea05a98fc
    Value: 40
    Address: 0x7ffea05a9900
    Value: 50

    C++ Array of Pointers

    An array of pointers refers to the array whose elements are pointer type that stores a pointer to an integer or char or any other data types in C++. These variables of pointers point to some other element.

    The declaration of array of pointers is done in the following way:

    int *ptr[10];

    In the above declaration, an array of pointer named ptr is created that that allocates 10 integer pointers in memory.

    We can also access or assign the variable through array of pointers such as:

    int x; // variable declaration.  
    ptr[3] = &x;  //assigning the address of x to 4th element  
    
    *ptr[2];  accessing the 3rd element

    Let us see it in a C++ program.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int number[5] = { 10, 20, 30, 40, 50 };
       int *ptr[5];
    
       // assign the address of number element tp ptr.
       for (int i = 0; i < 5; i++)
       {
          ptr[i] = &number[i];
       }
    
       //Displaying the value in ptr
       for (int i = 0; i < 5; i++)
       {
          cout << "number[" << i << "] = ";
          cout << *ptr[i] << endl;
       }
    
       return 0;
    }

    Output:

    number[0] = 10
    number[1] = 20
    number[2] = 30
    number[3] = 40
    number[4] = 50

    Array of Pointers to character

    We can use array of pointers to store a list of string in C++. Example:

    #include <iostream>
    using namespace std;
    
    int main()
    {
       const char *names[5] = { "Leanord Drest", "Zelda", "Tony Star", "Peter", "Steve" };
    
       for (int i = 0; i < 5; i++)
       {
          cout << "names[" << i << "] : " << names[i] << endl;
       }
    
       return 0;
    }

    Output: After execution, you will get the following result.

    names[0] : Leanord Drest
    names[1] : Zelda
    names[2] : Tony Star
    names[3] : Peter
    names[4] : Steve

  • C++ Pointers

    Pointer is an important part of the programming as it deals with the memory address of the variables. There are various tasks that can be achieved easily with the use of pointers in C++ such as dynamic memory allocation that needs pointers for its operation. It also minimizes the execution time and saves memory space. Arrays, function and structure also use pointers to manipulate the variables and parameters.

    Let us understand the memory address first.

    Memory Address:

    As we already know at this point that every variable declared in a program is stored in computer storage possessing some memory address. And these addresses can be accessed by using the ampersand (&) operator. If you have the variable name var then &var is used to access the address of that variable in a program.

    Let us see ampersand (&) in action.

    C++ program to print the address of variables using pointers.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        //variables declaration and initialization
        int var1 = 8;
        int var2 = 50;
    
        // printing the address with &
        cout << "Address of var1: "<< &var1 << endl;
        cout << "Address of var2: " << &var2 << endl;
    }

    Output:

    Address of var1: 0x7ffec209b710
    Address of var2: 0x7ffec209b714

    The address on displayed on your computer may be different. It address is in hexadecimal representation.


    C++ Pointer

    In programming, pointers refer to the symbolic representation of an address. Pointers are the variables that store the address of another variable (the variable the pointer is pointing to) rather than the value itself.

    Syntax of Pointer:

    Declaration of pointer in C++: Pointer variables are declared in the following way using asterisk * symbol ( asterisk * = same asterisk used for multiplication).

    //pointer declaration
    data_type *pointer_name;

    Example: You can declare the pointer with different C++ data-types too, some are:

    int    *intp; //pointer to an integer
    float  *fltp; //pointer to a float
    char   *chp   //pointer to a character

    Initialization of pointers

    After declaring the pointer, we need to initialize the pointers. To get the actual address we use the ampersand (&) operator and it is used before the variable name that pointer needed to be the point.

    pointer = &variable_name;

    Example:

    int *ptr;
    
    int x =10;
    x = 10;
    ptr= &x;

    • Reference operator (&): It returns the variable’s address.
    • Dereference operator (*): It gets the value that has been stored in a memory address.

    How to use a Pointer?

    • First, we define a pointer.
    • Then, assigning an address of a variable to a pointer using a Reference operator (&).
    • Lastly, with the use of Dereference operator (*), we access the value present at the address pointed by the pointer variable.

    Pointer Example

    Let us see a C++ program to print the address and the value with Pointers.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        //variables declaration and initialization
        int num = 10;
        int *ptr; //pointer variable 
        
        //ptr stores the address of num variable   
        ptr = &num; 
    
        // printing the address with &
        cout << "Address of num: "<< ptr << endl;
        cout << "Value of *ptr variable: " << *ptr << endl;
    }

    Output:

    Address of num: 0x7ffedcadffec
    Value of *ptr variable: 10

  • C++ Return Array from Functions

    C++ allows us to return the arrays from a function. However the actual array values cannot be returned, so we return the array from the function with the help of pointers.

    Pointers are the variables that hold an address. With the help of pointers, the address of the first element is returned from a function. The name of the array is itself points to the first element.

    In order to return the array from the function, we need to declare a function returning a pointer in a one-dimensional array. Example: syntax of returning function

    data-type * function_name() {
       .....
       .....
       .....
    }

    Also, C++ does not allow to return the address of the local variable from the function, so we need to declare the local variable as static in a function.


    Example of C++ Return Array from Functions

    #include <iostream>
    using namespace std;
    
    int *return_func()
    {
       // static declaration of array
       static int arr[10];
       for (int i = 0; i < 10; i++)
       {
          arr[i] = i;
       }
    
       //address of array returned
       return arr;
    }
    
    int main()
    {
       //pointer declaration
       int *ptr;
    
       ptr = return_func();	//address of a
    
       cout << "Printing an returned array: " << endl;
       for (int i = 0; i < 10; i++)
          cout << ptr[i] << " ";	//ptr[i] = *(ptr + i)
    
       return 0;
    }

    Output:

    Printing an returned array: 
    0 1 2 3 4 5 6 7 8 9 

  • C++ Multidimensional Arrays

    C++ allows Multi-Dimensional Arrays. This could be of 2D or 3D (two-dimensional or three-dimensional) Array. These arrays are stored in the form of a table (with rows and columns) which is also known as a matrix.

    In C++, multidimensional array is also known as rectangular arrays.

    Syntax of multi-dimensional array:

    data-type array_name[size1][size2]...[sizeN];

    The data-type must be a valid C++ data type, a unique name must be specified to each array and the size must be of an integer constant.

    //Two Dimensional array (2D)
    int arr[2][3];
    
    //Three Dimensional array (3D)
    int arr[2][4][6];

    Initialization of Multi Dimensional Array in C++

    We can initialize a Multi-Dimensional Array (two-dimensional or three-dimensional) in the following ways in C++.

    1. Initialization of two-dimensional array:

    The following is the 2 by 3 matrix array that is array with 2 rows and 3 columns.

    //Method 1
    int arr[2][3] = { {4, 5, 7}, {8, 3, 20} };
    
    OR
    
    //Method 2
    int arr[2][3] = {4, 5, 7, 8, 3, 20};

    There are two ways shown above to initialize an 2D array. However the method 1 is not preferred.

    2. Initialization of three-dimensional array:

    //Method1
    int arr[2][3][4] = {
        {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
        {{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}
        };
    OR
    //method2
    int arr[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
                     11, 12, 13, 14, 15, 16, 17, 18, 19,
                     20, 21, 22, 23};

    Accessing two Dimensional array in C++

    Accessing 2d Array:

    An array can be accessed by using a specific index number. It can be achieved by placing the particular index number within the two brackets [][]. Such as:

    arr[2][3]; //the 4th element of the third row is accessed
    arr[3][2]; //the 3rd element of the fourth row is accessed
    OR
    int val = arr[2][3]; // assigning the element to val

    Accessing 3d Array:

    Accessing 3-dimensional array is also as same as a two-dimensional array, the only difference is that in 3d array we have to specify 3 subscripts with a required index number.


    Example of C++ Multi Dimensional Array:

    Example: Two Dimensional Array in C++

    C++ Program to display all elements in an 2D array

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int arr[3][2] = {
    		{ 10, 55 },
                    { 5, 7 },
                    { 18, -8 }
           };
    
       cout << "Displaying each element" << endl;
       //using nested loop to access 2D Array element
       for (int row = 0; row < 3; ++row)
       {
          for (int col = 0; col < 2; ++col)
          {
             cout << "arr[" << row << "][" << col << "] = " << arr[row][col] << endl;
          }
       }
    
       return 0;
    }

    Output:

    Displaying each element
    arr[0][0] = 10
    arr[0][1] = 55
    arr[1][0] = 5
    arr[1][1] = 7
    arr[2][0] = 18
    arr[2][1] = -8

    Example: Three Dimensional Array in C++

    C++ Program to display all elements in an 3D array

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int arr[2][3][2] = {
    		{
             { 4, 8 },
             { 2, 4 },
             { 1, 6 }
          },
          {
             { 3, 6 },
             { 5, 4 },
             { 9, 3 }
          }
       };
    
       cout << "Displaying each element" << endl;
       //using nested loop to access 3D Array element
       for (int i = 0; i < 2; ++i)
       {
          for (int j = 0; j < 3; ++j)
          {
             for (int k = 0; k < 2; ++k)
             {
                cout << "arr[" << i << "][" << j << "][" << k << "] = " << arr[i][j][k] << endl;
             }
          }
       }
    
       return 0;
    }

    Output:

    Displaying each element
    arr[0][0][0] = 4
    arr[0][0][1] = 8
    arr[0][1][0] = 2
    arr[0][1][1] = 4
    arr[0][2][0] = 1
    arr[0][2][1] = 6
    arr[1][0][0] = 3
    arr[1][0][1] = 6
    arr[1][1][0] = 5
    arr[1][1][1] = 4
    arr[1][2][0] = 9
    arr[1][2][1] = 3

    As we saw the examples of 2D and 3D arrays, in a similar we can create any number dimension as required. However, the most used multidimensional array is a two-dimensional array.


  • Passing Array to a Function in C++

    In C++, passing an array to a function in the one-Dimensional array is done through an actual parameter and array variables with subscript are passed as formal arguments. While passing the array only the name of the array is passed to the function.

    Same method is applied for the multi-dimensional array.

    The syntax for passing an array to a function: There are three methods that can be used to pass an array to a function.

    First Way: As a unsized array

    return_type function(type arrayname[])
    {
      .....    
    }

    Second Way: As a sized array

    return_type function(type arrayname[SIZE])
    {
      .....    
    }

    Third Way: As a pointer

    return_type function(type *arrayname)
     {
      .....    
     }

    C++ Program for Passing One-dimensional Array to a Function

    The following program find the sum of all the numbers present in an array of one-dimensional.

    // C++ Program to find the sum of all the numbers
    
    #include <iostream>
    using namespace std;
    
    // function to add and return result
    int sumFunc(int arr[], int size)
    {
       int sum = 0;
    
       for (int i = 0; i < size; ++i)
          sum += arr[i];
    
       return sum;
    
    }
    
    int main()
    {
       // declaring and initializing an array
       int num_array[5] = { 20, 55, 18, 68, 10 };
       int result;
    
       //aclling a function by passing array and size
       result = sumFunc(num_array, 5);
    
       cout << "The sum of all numbers: " << result << endl;
    
       return 0;
    }

    Output:

    The sum of all numbers: 171

    C++ Program for Passing Multidimensional Array to a Function

    // C++ Program to display the 2D array elements
    
    #include <iostream>
    using namespace std;
    
    void displayFunc(int arr[][2], int row, int col)
    {
       cout << "Elements present in an Array: " << endl;
       for (row = 0; row < 3; ++row)
       {
          for (col = 0; col < 2; ++col)
          {
             cout << "arr[" << row << "][" << col << "]: " << arr[row][col] << endl;
          }
       }
    }
    
    int main()
    {
       // initialize 2d array
       int num[3][2] = {
    		{ 6, 9 },
          { 5, 4 },
          { 3, 2 }
       };
    
       // call the function
       displayFunc(num, 3, 2);
    
       return 0;
    }

    Output:

    Elements present in an Array: 
    arr[0][0]: 6
    arr[0][1]: 9
    arr[1][0]: 5
    arr[1][1]: 4
    arr[2][0]: 3
    arr[2][1]: 2

    Note: It is mandatory to give the column value in formal parameters but it is not necessary to give a row value. That is why int arr[][2] is written. We inserted 2 in the column value.


  • C++ Arrays

    An array is a group or a fixed-size sequential collection of data having the same data-type stored in a contiguous memory location. It is a simple data structure format where the primitive type of data such as int, char, double, float, etc are stored and accessed randomly through their index number such as array[0], array[1], etc.

    It can also store the collection of derived data types, such as pointers, structure, etc. Elements are arranged inside the array with index numbers starting from zero as the first elements.

    Types of Array in C++:

    • One Dimensional Array
    • Multi-Dimensional Array

    C++ Array Declaration

    For declaration of an array in C++, the user needs to specify the type of element and number of elements in an array. Below is the declaration of the single-dimensional Array.

    type array_name[arraySize];

    The data type must be a valid C++ data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for an integer array with 20 elements.

    int arr[20];

    C++ Array Initialization

    An array can be initialized by using a single statement or one by one. The Initialization is done within the curly braces {}. The example below is the initialization of single-dimensional Array.

    int arr[5] = {20, 50, 77, 13, 48};
    OR
    int arr[] = {20, 50, 77, 13, 48};

    In the second one of the above example, the array size is not declared so that you can initialize as much value as you want.

    Users can also directly assign the value to the particular element in an array by specifying the index number such as: below shows how to assign the value 20 to the 3rd element of an array.

    arr[2] = 20;

    NOTE:
    In the above example, number 2 means the 3rd element as the array index starts from 0.


    Accessing Array Elements in C++

    As told above, that each array elements are associated with specific number that is the index numbers.

    An array element can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:

    //Accessing single-dimensional Array
    arr[3]; //the 4th element is accessed
    arr[7]; //the 8th element is accessed

    We can also assign the value particular index number to other variable but their data type must be the same such as:

    int numb = arr[3];

    In the above, the value of 4th element from an array arr[] is assigned to the numb variable.


    Example: C++ Program to show the declaration, initialization and accessing of an array

    #include <iostream>
    using namespace std;
    
    int main() 
    {
        //initialization and declaration
        int arr[5] = {20, 50, 77, 13, 48};
    
        cout << "The elements are: " << endl;
        for (int i = 0; i < 5; ++i) {
            cout << arr[i] << endl;
        }
    
        cout << "Accessing 4th element: " << arr[3]; //accessing 4th element
    
    
        return 0;
    }

    Output:

    The elements are: 
    20
    50
    77
    13
    48
    Accessing 4th element: 13

    Empty Members in an array – C++

    When we declare an array of size n, that means we can store the n number of elements of in that array. But what happens if we were to store less than n number of elements.

    Consider an example below:

    //size=10
    //stored = 6 elements
    int arr[10] = {19, 10, 8, 45, 2, 87};

    As you can see, the size of an array is 10 but we initialized it with only 6 elements. However, a 10 contiguous memory location is already allocated to this array. What will happen to the remaining un-initialized arrays?

    Now in such cases, random values are assigned by the compiler to the remaining places. And often these random values are 0.


    Index Out of bound : Accessing elements out of it bound.

    Out of bound means, suppose you declare an array with 5 number of elements (index between 0 to 4) and you try to access the 7th element, which is not present in that array such as:

    .........
    ........
    {
       int arr[5];
     
       cout << arr[7] << endl;
       .......
    }

    In the above program, the 7th element is not present but we are trying to print that element. In such cases, the program may run fine but you may get an unexpected output (undefined behavior) from a program.

    There is no index out of bounds checking in C++.


    Advantages of Array in C++

    • Less line of codes that is a single array with multiple elements, specifying code optimization.
    • Elements of an array can be accessed randomly with the index number.
    • The elements in an array can be easily traversed.
    • Array’s data are easy to manipulate.
    • Sorting becomes easy in an array with fewer lines of codes.

    Disadvantages of Array in C++

    • The array is of fixed size once initialized. We cannot add new elements after initialization.
    • The number of elements you need to store in an array must be known in advance.
    • There may be a wastage of space if more memory is allocated than the required amount.

    Arrays in C++

    There is more to the arrays, click on the below to learn them separately in detail.

    C ++ Multi-dimensional Array
    C++ Passing Array to a Function
    C++ Return Array from Functions

  • C++ Recursion

    Recursion refers to the process when a function calls itself inside that function directly or indirectly or in a cycle. And such functions are called recursive functions. However, the crucial part is the termination condition, if not handled properly then it might go into an infinite loop.

    void recursion()
    {
        ......
        recursion(); //calling itself
        ......
    }
    
    int main()
    {
        ......
        recursion();
        ......
    }
    Recursion

    We can use the if…else statement to stop it from going into an infinite loop. Using the if…else statement, one branch of if-else can call the function itself and the other can give the condition to end the function.


    Example: C++ Recursion Program

    Program to find the factorial of a number in C++ using recursion.

    #include <iostream>
    using namespace std;
    
    int factorialFunc(int);
    
    int main()
    {
       int fact, num;
    
       cout << "Enter a positive integer: ";
       cin >> num;
    
       //calling factorial function
       fact = factorialFunc(num);
    
       cout << "Factorial of " << num << " is: " << fact << endl;
       return 0;
    }
    
    int factorialFunc(int n)
    {
       if (n == 0)
          return (1);  //base condition
       else
       {
          return (n* factorialFunc(n - 1));	//recursion
       }
    }

    Output:

    Enter a positive integer: 5
    Factorial of 5 is: 120

    If you want to learn more about recursion in detail, click here. Although it is for C programming but the theory concept of recursion is the same for all programming languages.


  • C++ Storage Classes

    What is Storage Class in C?

    Storage class is used to define the scope and lifetime of a variable. It tells the compiler where to allocate memory for a variable.

    Every variable in C++ has a type and the storage class. The type defines its data types such as int, float, etc. While storage defines two features such as scope and lifetime of a variable.

    A lifetime of a variable refers to the period of its activeness and visibility refers to the accessibility of a variable in a program.

    C++ program uses the following storage class:

    • Automatic
    • Register
    • Static
    • External
    • Mutable

    Automatic(auto) Storage class:

    A variable defined within a function or block with an auto specifier belongs to the automatic storage class. Auto variables can only be accessed within the block/function where they have been declared and not outside them which defines their scope.

    These are also referred to as local variables. By default, the variable declared in a program is auto storage variables and if they are not assigned then they hold a garbage value.

    auto keyword is used to defined an auto storage class in a program.
    Example:

    auto int number;
    //Example
    
    {
       auto int num;  
       float num = 3.45;  
    }

    The above defines a auto variable that are only accessible within those curly braces.

    C++ Program for auto storage class

    #include <iostream>
    using namespace std;
    
    //user-defined funciton
    void autoStorage()
    {
       // auto variables
       auto x = 20;
       auto y = 50;
    
       //displaying
       cout << "x: " << x << " \n";
       cout << "y: " << y << " \n";
    }
    
    int main()
    {
       //calling a function
       autoStorage();
    
       return 0;
    }

    Output:

    x: 20 
    y: 50 

    Now if you try to access the x or y variables through the main function, you will get an error indicating the scope of x and y is within the autoStorage() function only.


    Register Storage class:

    Register storage class is only for those variables that are being used very often in a program. The reason is, there are very few CPU registers at our disposal and many of them might be busy processing or something else. A typical application of the register storage class is loop counters, which get used a number of times in a program.

    Just like auto storage, it has the scope to a limited block where it is used. The difference is that the variables declared with a register keyword are stored in the register memory instead of RAM memory for quick access.

    It also means that the variable size is equal to the register size, usually one word.

    Note: We cannot get the memory location when dealing with the CPU register. If you use pointers to access the memory location, the program will through an error.

    Registers are declared as:

    register int variable_name;

    Static Storage Class:

    The keyword static is used to declare this type of variables in a c++ program. The name static is given to variables that can hold their values between calls of a function. They are allocated only once and their values are preserved between any number of function calls.

    Space is allocated for static variables in the program code itself and hence no new memory is allocated to it as they are not re-declared in the program.

    Their scope is local to the function where they are defined. Also, a global static variable can be accessed anywhere throughout the program.

    The static variable has the default value 0 which is provided by compiler.

    NOTE: Every global variable, defined outside functions has the type static automatically. The opposite of static is auto.

    C++ program of static storage class

    #include <iostream>
    using namespace std;
    
    //global variable
    static int count = 5;
    
    // Function
    void staticFunc(void)
    {
       // local static variable
       static int temp = 1;
       temp++;
       cout << "temp is: " << temp << ",  count is: " << count << endl;
    }
    
    
    int main()
    {
       while (count--)
       {
          staticFunc();
       }
    
       return 0;
    }

    Output:

    temp is: 2,  count is: 4
    temp is: 3,  count is: 3
    temp is: 4,  count is: 2
    temp is: 5,  count is: 1
    temp is: 6,  count is: 0

    External(extern) Storage Class:

    Extern stands for external storage class. The principal use of extern is to specify that a variable is declared with external linkage elsewhere in the program. In general, it is used to declare a variable to be used in a module that is not the one in which the corresponding variable is defined.

    extern keyword is used to define the global variable whose scope is within the whole program, which means these variables are accessible throughout the program.

    The main purpose of using extern is that they can be accessed between two different files which are located apart in a large program providing the reference of the variable. Check the program below to understand clearly.

    extern int variable_name;

    C++ program for extern storage class

    We will create two C++ file and access the variable/function of one file to another with static keyword.

    First file: main.cpp

    #include <iostream>
    
    int temp;
    
    //accessed using extern
    extern void extern_example();
     
    main() 
    {
       temp = 10;
       write_extern();
    }

    Second file: test.cpp

    #include <iostream>
    using namespace std;
    
    //this count variable is declared in main.cpp
    //here it accessed by using extern
    extern int temp;
    
    //some user-defined function
    void extern_example(void) 
    {
       cout << "Count is " << temp << endl;
    }

    Output:

    10

    As you can see, the variable of main.cpp file is accessed in test.cpp file using extern keyword and extern_example() function of test.cpp file is accessed in main.cpp file.


    mutable Storage Class

    mutable keyword is used for some specific task such as to modify one or more data members of class/struct through const function. This specifier is applied to only class objects.

    If we summarize all of the in a table, we will get,

    Storage ClassLifetimeVisibilityDefault Value
    Automatic (auto)Function BlockLocalGarbage
    Register (register)Function BlockLocalGarbage
    External (extern)different program
    files
    GlobalZero
    Static (static)Whole ProgramLocalZero
    Mutable (mutable)ClassLocalGarbage

  • Call by Value and Call by Reference in C++

    There are two ways in which the argument can be passed through a function in C++ Programming.

    1. Call by Value
    2. Call by Reference

    Let’s go through call by value and call by reference in C++ language one by one.


    C++ call by value

    The method of call by value copies the actual argument to the formal parameter of the function. In this case, the changes made to the formal parameters within the function will not be affect the actual argument that is original value is not modified.

    By default, C++ programming uses call by value to pass arguments.

    Let us understand the call by value with an example in C++

    Example: Swap the values of two variables in C++ Programming:

    #include <iostream>
    using namespace std;
    
    // function declaration and definition together
    void swapFunc(int x, int y)
    {
       int temp;
    
       temp = x;
       x = y;
       y = temp;
    
       return;
    }
    
    //main function
    int main()
    {
       int a = 10;
       int b = 20;
    
       cout << "Before swap, a: " << a << endl;
       cout << "Before swap, b: " << b << endl;
    
       //calling function by passing a and b
       swapFunc(a, b);
    
       cout << "\nAfter swap, a: " << a << endl;
       cout << "After swap, b: " << b << endl;
    
       return 0;
    }

    Output:

    Before swap, a: 10
    Before swap, b: 20
    
    After swap, a: 10
    After swap, b: 20

    C++ Call by Reference

    Here reference refers t the addresses but not the actual value. In this method, we pass the reference of the argument to the formal parameter.

    Since the actual and formal parameters share the same address, the changes made inside the function will be reflected outside the function too. Hence, the original value is modified.

    we know that the reference that is the is dealt through the pointers in a program. to understand the call by reference type, you need to have basic knowledge of pointers.

    Let us understand the call by reference with an example in C++

    Example: Swap the values of two variables in C++ Programming:

    #include <iostream>
    using namespace std;
    
    //user-defined function
    void swap(int *x, int *y)
    {
       int swap;
    
       swap = *x;
       *x = *y;
       *y = swap;
    }
    
    //main function
    int main()
    {
       int a = 100, b = 200;
    
       cout << "Before swap, a: " << a << endl;
       cout << "Before swap, b: " << b << endl;
    
       //calling a value by passing reference  
       swap(&a, &b);
    
       cout << "\nAfter swap, a: " << a << endl;
       cout << "After swap, b: " << b << endl;
       return 0;
    }

    Output:

    Before swap, a: 100
    Before swap, b: 200
    
    After swap, a: 200
    After swap, b: 100

  • C++ Functions

    A function refers to a block of code (or a group of statements) that performs a specific task. A function takes some inputs, does some computation based on that input and returns the output. The function can be called many times by passing different values each time.

    For example, let us say that you need to compute a complex multiplication for different values on a different part of a program. One thing you can do is repeat the block of code for computation again and again, which is not a good practice as a programmer and makes the program complex and time-consuming. Better you can create a function and call that function every time you need by passing the different values.

    Every C++ program has at least one function which is always executed and that is the main function from where the execution of the program begins. The function is declared within the curly braces {}.


    Advantages of functions in C++

    There are many advantages of using function in C++.

    Reusability of code: As mention above in the example, we can reuse the function by calling it again and again as required in the program.

    Optimization of Code: Use of functions makes the program short and simple to understand. You only need to write the logic of the calculation once and use it several times.


    C++ function is defined into two categories:

    1. Standard Library Functions
    2. User-defined functions


    1. C++ Standard Library Functions

    These are the pre-defined function in a C++ program, like a main function. These built-in functions are already defined and written in C++, to use them you just need to invoke or call them directly.

    Some common library functions in C++ are sqrt()abs()isdigit(), etc.

    To use these library functions an appropriate header file needs to be included in the program. Example: to use math functions such as sqrt(), you need to include cmath header file.

    Example of C++ Standard Library Functions:

    #include <iostream>
    #include <cmath>  //math header file to use maths library function
    using namespace std;
    
    int main()
    {
       double number, square_result;
    
       cout << "Enter the number: ";
       cin >> number;
    
       //here sqrt() is a library function that calculates the square root
       square_result = sqrt(number);
    
       cout << "The square root of " << number << " is: " << square_result;
       return 0;
    }
    //Output:
    
    Enter the number: 625
    The square root of 625 is: 25

    2. C++ User-defined functions

    These are the functions created by the programmer in order to use it as many times as required. The user or programmer writes a block of code inside a body of a function to do some specific task.

    These functions can also be called or invoke from any part of the program and code inside the body of that function will be executed.

    We will see the examples of both Library Functions and User-defined functions below in this article.

    Example of C++ User-defined Functions:

    #include <iostream>
    using namespace std;
    
    //user-defined function
    int sum(int a, int b = 5)
    {
       int result;
       result = a + b;
    
       return result;
    }
    
    //Main function
    int main()
    {
       int a = 10, b = 20, result;
    
       // calling a function by passing a and b
       result = sum(a, b);
       cout << "Sum result: " << result << endl;
    
       // calling a function again by passing only a
       //In this case b will be added through the function defined above
       result = sum(a);
       cout << "Sum result: " << result << endl;
    
       return 0;
    }
    //Output:
    
    Sum result: 30
    Sum result: 15

    Function Declaration or Prototype:

    Declaring a function means telling the compiler about the function name and its return type and parameters (if any). it is like stating the prototype of the function.

    In C++, the function declaration declares a function without a body. It is important to declare the function when you are using one of the source file function to another file. We declare the function at the top of the program.

    The syntax for function declaration:

    return_type function_name( parameter list );

    Example:

    int max(int, int);
    
    //function that takes a ponter and integer
    int *swap(int*,int);

    Note: Also note that, if you defined the function before the main function then the separate function declaration is not required in a program else you need to mention the declaration. Example: In the syntax below, a declaration is not required

    #include <iostream>
    using namespace std;
    
    //user-defined function
    int sum(int a, int b = 5)
    {
    
       ...........
       ...........
    
     
       return result;
    }
    
    //Main function
    int main()
    {
       .............
       .............
    
       // calling a function
       result = sum(a, b);
       ............
       .............
    
       return 0;
    }

    Function Definition

    Generally, the function is defined in following way in C++:

    return_type function_name( parameter_list ) {
       body of the function;
    }

    Each part of a function:

    • Return type: A function may return a value unless it is a void function, which does not return any type of value. return_type is a data type of the function. It could return arithmetic values (int, float, etc.), pointers, structures, etc.
    • Function name: Function name refers to identifiers through which function can be identified uniquely. It is a function’s name that is stated to function by following some naming rules.
    • Parameter list: Parameter is also referred to as Argument. We can pass the values through the parameter when the function is invoked. The parameter list refers to the type, order, and number of the parameters of a function
    • Function Body: The function body is enclosed within the curly braces’{}’. It defines the task of a method within the curly braces.

    Note: The function declaration and definition is for the user-defined type function only because the library function is already declared and defined. We just need to call the library function in order to use it.


    Function Call

    We need to call the function in order to use it. To call a function we simply write the function name by passing the values as parameters (if any).

    When the function is called, the execution control passes to the function and does some specific task. When the return statement of the function is executed or when it executes the end braces, it means the program control is returned to the main function.

    Following is the syntax t call a function.

    function_name( parameter_list );

    Example: How to declare and define a function and call the function in C++

    #include <iostream>
    using namespace std;
    
    //declaring a function
    int sumFunc(int, int);
    
    //Main FUnction
    int main()
    {
       int x, y, sum;
    
       cout << "Enter two numbers to add: ";
       cin >> x >> y;
    
       //calling a function by passing x and y
       sum = sumFunc(x, y);
    
       cout << "The addition of " << x << " and " << y << " is: " << sum;
       return 0;
    }
    
    //function definition
    int sumFunc(int num1, int num2)
    {
       int result = num1 + num2;
       return result;  //returning the result to main funciton
    }

    Output:

    Enter two numbers to add: 10 20
    The addition of 10 and 20 is: 30

    Function Arguments

    The function is called by passing some values, and the function must declare variables in order to accept those values of the argument. These variables are called a formal parameters of the function and created during the entry of the function.

    The actual arguments refers to the values passed while calling the function.

    There are two ways in which the argument can be passed through a function:

    • Call by Value.
    • Call by Reference.

    Click here to learn about them in detail.