• Home
  • 6.9 Passing by Value

6.9 Passing by Value

View Categories

6.9 Passing by Value

1 min read

Table of Contents

Passing by value means that a function receives a copy of the argument supplied by the caller. Changes made to the parameter inside the function do not affect the original variable.

This is the default parameter-passing mechanism for ordinary non-reference parameters in C++. It provides isolation between the function’s local parameter and the caller’s original object.

Source Code #

#include <iostream>

void updateValue(int value)
{
    value = 100;

    std::cout << "Inside Function: " << value << '\n';
}

int main()
{
    int number = 50;

    updateValue(number);

    std::cout << "Outside Function: " << number << '\n';

    return 0;
}

Output #

Inside Function: 100
Outside Function: 50

Explanation #

  • updateValue(int value) defines a function with an int parameter named value.
  • updateValue(number) passes the value stored in number to the function.
  • Because value is passed by value, the function receives a copy of number.
  • value = 100; modifies only the local copy inside the function.
  • The original number variable remains unchanged.
  • The value displayed inside the function is therefore 100.
  • After the function returns, number still contains its original value, 50.
  • Passing by value is useful when a function should work with a value without modifying the caller’s original variable.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *