ILWC Privacy Statement About ILWC
passing a value or passing an address
2019-02-26 18:50:44
2019-02-26 19:00:00
2019-03-26 19:00:00
I just wanted to make sure....soe C pass a parameter by value or by address.... According to below example I say "by value".

Let's have a look at the code:
[martijn@radijs misc]$ cat param.c

//In this function the address of a variable is passed
void change_param_b(int * a){

  printf("change_param_b : a : %i\n", *a); 
  //Let's add 1 to the value at the address
  printf("change_param_b : b : %i\n", *a);


//In this function the value of a variable itself is passed
void change_param_a(int a){

  printf("change_param_a : a : %i\n", a);  
  //let's add 1 to this value
  printf("change_param_a : b : %i\n", a);


int main(int argc, char ** argv){as expected, a has a value of 0

  int a;

  //have a look add the variable a at all the stages of the program  
  printf("main : a :%i\n", a);
  printf("main : b : %i\n", a);
  printf("main : c : %i\n", a);
  return 0;

Now compile it:
[martijn@radijs misc]$ gcc -o param param.c

And finally run it:
[martijn@radijs misc]$ ./param
main : a :0            <-- a has a value of 0
change_param_a : a : 0 <-- within param_a a starts with a value of 0
change_param_a : b : 1 <-- then, as expected, a ha a value of 1
main : b : 0           <-- however...back in main a has a value of 0
change_param_b : a : 0 <-- within param_b starts with a value of 0
change_param_b : b : 1 <-- The value is increased by the function
main : c : 1           <-- back in main a is still 1
[martijn@radijs misc]$ conclusion: c passes parameters by value.

As we can see in function param_a() the value of a is passed. Whitin the function this value is altered. When returned back to the main program the original value is still there. Only in the function the value was changed.

When using param_b() the address of a is passed. The function then alters the value of the integer stored at the passed address.
This is (ofcourse) seeable for the mainprogram, since the whole program sees the same address-space.