![]() |
VOOZH | about |
When we write functions in C, we often need to pass data from one function to another. Sometimes we just want the function to use the data without changing it, while other times we want the function to modify the original data. So there are two ways to pass parameters to functions.
Please note that the C language only supports pass by value. We achieve pass by reference effect with the help of pointer feature of C. In C++, we can either use pointers or for pass-by-reference.
In pass by value, the function receives a copy of the variable's value.
Before function call: 50 After function call: 50
In pass by reference, the function receives the address of the variable instead of a copy.
Before function call: 50 After function call: 60
Pass By Value | Pass By Reference |
|---|---|
A copy of the variable is passed in the function. | The address of the variable is passed in the function. |
Original variable is not affected. | Changes are reflected in the original variable. |
Two separate memory locations exist (original + function copy) | Only one memory location is shared. |
Function parameter is a normal variable | Function parameter is a pointer (*) |
Use when you want to protect original data. | Use when you want to modify original data. |
Example: void func( int x) | Example: void func(int *x) |