In one of my course's tutorial videos, I have encountered a situation where pass by value and pass by reference is occurring. In the example he gives us, he, firstly, admits that the code is written poorly, and then asks us to find out what exactly would be printed. The relevant code is as follows:
void set_array(int array[4]);
void set_int(int x);
int main(void){
int a = 10;
int b[4] = {0, 1, 2, 3);
set_int(a);
set_array(b);
printf("%d %d\n", a, b[0]);
}
void set_array(int array[4]){
array[0] = 22;
}
void set_int(int x){
x = 22;
}
What I want to make sure, after initially coming up with the wrong output, is that I'm understanding why the correct output of "10, 22" is being printed.
The value of 10 is being printed because when the set_int function is being called, its parameter, being a variable, means that any variable can be passed. It is not exclusive to only the value 22 as defined in the set_int function.
The value of 22 is being printed because, when the set_array function is being called, its parameter, being an array, means that only the original value can be passed because it points to a specific memory location where the value 22 is stored.
Have I misunderstood what is happening, and am I missing any crucial points?
By Definition, there is no pass-by-reference in function calls in C. Both your examples use pass by value. However, depending on the usage, the result varies (i.e., we can emulate the behavior of passing by reference).
In the first case, the variable a
is passed by value, hence it cannot be changed from the function call.
In the second case, the variable b
is passed by value, hence it is also cannot be changed from the function call.
However, in the second case, there is a special phenomena that takes place. The argument which is passed, b
is an array. An array, while passed as function argument (among many other usage), decays to a pointer to the first element of the array. So essentially, you're passing a pointer, and that value at the memory address pointed to by the pointer can be modified (but not the pointer itself). That's why, the change from the set_array()
function persists in the main()
.
In another word, the second case is equivalent to
void set_pointer(int *ptr);
void set_int(int x);
int main(void){
int a = 10;
int b[4] = {0, 1, 2, 3);
int * p = &(b[0]); // address of the first element
set_int(a);
set_pointer(p); // pass the pointer
printf("%d %d\n", a, b[0]);
}
void set_array(int *ptr){
*ptr = 22; // operate on pointer
}
void set_int(int x){
x = 22;
}