How to Pass by Value in C++: Syntax and Examples
In C++, you pass by value by declaring a function parameter with the type only, like
void func(int x). This means the function gets a copy of the argument, so changes inside the function do not affect the original variable.Syntax
To pass a parameter by value, declare the function parameter with the type only, without any reference or pointer symbols.
- Type: The data type of the parameter (e.g.,
int,double,std::string). - Parameter Name: The variable name used inside the function.
- Function Body: The code that uses the copied parameter.
Example syntax:
cpp
void functionName(Type parameterName) { // function code using parameterName }
Example
This example shows a function that takes an integer by value and modifies it inside the function. The original variable outside the function remains unchanged.
cpp
#include <iostream> void addFive(int num) { num = num + 5; // modifies the copy std::cout << "Inside function: " << num << std::endl; } int main() { int value = 10; addFive(value); std::cout << "Outside function: " << value << std::endl; return 0; }
Output
Inside function: 15
Outside function: 10
Common Pitfalls
Passing by value copies the argument, which can be inefficient for large objects like big structs or classes. Also, changes inside the function do not affect the original variable, which might confuse beginners expecting the original to change.
Wrong approach if you want to modify the original variable:
cpp
// Wrong: changes do not affect original void increment(int x) { x = x + 1; // only changes the copy } // Right: use reference to modify original void increment(int &x) { x = x + 1; // changes the original variable }
Quick Reference
Passing by value means the function works with a copy of the argument.
- Use when you want to protect the original data from changes.
- Good for small data types like
int,char,float. - Not efficient for large objects; consider passing by reference instead.
Key Takeaways
Passing by value copies the argument, so the original variable is not changed.
Use simple syntax:
void func(Type param) to pass by value.Passing large objects by value can be slow; prefer references for efficiency.
Changes inside the function affect only the copy, not the original variable.
Use pass by value when you want to keep the original data safe from modification.