Signup/Sign In

C++ Pass By Value Program

Hello Everyone!

In this tutorial, we will learn the working of a Pass By Value function call, in the C++ programming language.

Pass by Value Function Call:

In this type of Function Call, only the actual value of the variable is passed to the function that has been called instead of the address at which that value is stored. As a result, any changes made to the variable are only local to the method that has been called unless the variable is declared as a global variable.

To learn more about this concept, visit https://www.studytonight.com/cpp/call-by-value-and-reference.php, where we have explained the difference between call by value and call by reference function calls.

For better understanding, refer to the well-commented code given below.

Code:

#include <iostream>
#include<vector>
using namespace std;

//Function prototyping as defined after it is being called
int sumOf(int, int);

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to demonstrate the Pass By Value Function Call, in CPP  ===== \n\n";

    //variable declaration
    int num1, num2, addition=0;

    cout << "Enther the two numbers you want to add : \n\n";
    cin >> num1;
    cin >> num2;

    /*
    Demonstrating Multi-line Commenting:
        Passing the values stored in the variables num1 and num2 as parameter to function sumOf().
        The value returned by the function is stored in the variable output
    */

    addition = sumOf(num1, num2);
    cout << "\n\nThe Sum of the two numbers " << num1 << " and " << num2 << ", returned by the function sumOf(), is = " << addition;

    cout << "\n\n\n";

    return 0;
}


// Defining the function sumOf(a,b) which is called by Passing Values and returns the sum of a and b
int sumOf(int n1, int n2)
{
    int sum;
    //Computing the addition of the two values the function is called with
    sum = n1 + n2;

    //Returning the addition to the point where this function is called from
    return sum;
}

Output:

C++ Pass By Value

We hope that this post helped you develop a better understanding of the concept of Call by Value in CPP. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.