C++ Call by Value

In C++, call by value passes a copy of the argument to the function. Changes made inside the function do not affect the original variable in the caller.

1. Call by Value Syntax

The function receives a copy of the argument, so modifications inside the function do not affect the original variable.

C++
return_type function_name(data_type parameter) {
    // function body
}

2. Call by Value Example

This example demonstrates call by value where changes inside the function do not affect the original variable.

C++
#include <iostream>
using namespace std;

void increment(int a) {
    a = a + 1;
    cout << "Inside function: " << a << endl;
}

int main() {
    int x = 5;
    increment(x);
    cout << "Outside function: " << x << endl;
    return 0;
}

3. Common Mistakes

Expecting changes in the original variable when using call by value is a common mistake. Always remember that only a copy is modified inside the function.

Conclusion

C++ call by value passes copies of variables to functions, ensuring the original data remains unchanged. It is useful when you want to protect the original data from modification.