11 printf("a: %d, b: %d\n", a, b);
12 }
•
Pass-by-reference prevents the value from being copied and instead tells the function to directly
modify the variable stored in the caller’s scope
– This is clearly useful!
–
So far, we’ve only been able to return a single data type, but if we can modify parameters in
the caller’s scope, we have a way to “return” multiple values by telling the parameters “not
to copy” into the function’s scope.
• But C does not support this.
• Fortunately, pointers are just memory addresses.
• If you copy a pointer, the memory location says the same.
• This means we can create pass-by-reference behavior by passing pointers to functions
–
The pointers are copied into the function, but if we dereference and modify their value, we
aren’t changing the pointer, but the contents the pointer refers to.
– This is essentially pass-by-reference behavior
– In the notes on arrays, we actually never needed to return the array! For instance:
1 //NOTICE: the asterisk (star) next to int indicates we are returning an
array
2 int* add_to_zeroth_element(int arr[], size_t arr_len, int value){
3 // this is just a dummy array operation, in practice you'll do
wonderful and amazing things here
4 arr[0] += value;
5 // NOTICE: return the array, we don't use [] here, just the name of
the array.
6 return arr;
7 }
8
9 void add_to_zeroth_element_no_return(int *const arr, size_t arr_len,
int value){
10 // this is just a dummy array operation, in practice you'll do
wonderful and amazing things here
11 arr[0] += value;
12 // don't need
13 }
14
15 int main(){
16 int arr[] = {1,2,3};
17 // notice the type here has to match the return type of the function.
Exactly what's going on here will be covered with pointers.
10