pass by value and pass by reference

Thread Starter

Parth786

Joined Jun 19, 2017
642
Hi all

In c we can pass the parameters in a function in two different ways.

1. pass by value
2. pass by reference

pass by value
Code:
void PassByValue(int value)
{
    // code 
}
pass by reference
Code:
void PassByReference(int* reference)
{
    //code 
}
what is Difference between pass by value and pass by reference. I have seen some example on internet but for better understanding if someone can help with example. it would much appreciated
 

jayanthd

Joined Jul 4, 2015
945
In pass by value you pass the actual value to the argument of the function.

In pass by reference you pass the address of the variable which holds the value.

Inside the function you will dereference the pointer to get the value.

Pass by value example:

unsigned int g_value = 0;
unsigned int my_value = 2;

unsigned int my_get_value_function_1(unsigned int value) {
return (value * 2);
}

Code:
void main () {
      g_value = my_get_value_function_1(my_value);
      after function returns g_value contains 4.
}

Pass by ref example:

unsigned int g_value = 0;
unsigned int my_value = 2;

unsigned int my_get_value_function_2(unsigned int value) {
return (*value * 2);
}

Code:
void main () {
      g_value = my_get_value_function_2(&my_value);
      after function returns g_value contains 4.
}
 
Top