Passing arguments to functions by reference (using pointers).

Lesson 4.3: Passing Arguments to Functions by Reference (Using Pointers)


In this lesson, you'll learn a powerful technique in C: passing arguments to functions by reference. This allows you to modify the original variables passed to a function, not just copies of their values.  You'll accomplish this using pointers.


Review: Pass by Value (Default Behavior)


Recall that C typically passes function arguments by value. This means the function receives a copy of the argument's value.  Any changes made within the function remain local and don't affect the original variable.


C

void changeValue(int num) {

    num = 100; // Modifies the local copy, not the original

}


int main() {

    int x = 5;

    changeValue(x);

    // x still equals 5

}

Pass by Reference with Pointers


Pass the Address: Instead of passing the value, you pass the memory address of the variable using the address-of operator (&).

Receive a Pointer: The function receives a pointer parameter (a variable that stores an address).

Dereference the Pointer: Inside the function, use the indirection operator (*) to access and modify the value at the memory address the pointer holds.

Example:


C

#include <stdio.h>


void swap(int *a, int *b) {

    int temp = *a;

    *a = *b;

    *b = temp;

}


int main() {

    int x = 5, y = 10;

    printf("Before swap: x = %d, y = %d\n", x, y);


    swap(&x, &y); // Pass addresses of x and y


    printf("After swap: x = %d, y = %d\n", x, y);

    return 0;

}


Output:


Before swap: x = 5, y = 10

After swap: x = 10, y = 5

Explanation:


In main, we declare x and y and pass their addresses (&x and &y) to the swap function.

swap receives these addresses in pointers a and b.

Inside swap, *a and *b are used to access and modify the values at the addresses held by a and b (which are the locations of x and y).

The swap operation directly modifies the original variables.

Why Pass by Reference?


Modifying Multiple Values: If you need a function to modify more than one variable, pass by reference is essential.

Large Data Structures: Passing by reference avoids expensive copying of large data structures (e.g., arrays, structures).

Efficiency: For small data types, the performance difference between pass by value and reference might not be significant. However, for large data structures, passing by reference can lead to noticeable efficiency gains.

Key Points:


&: (Address-of Operator): Used when calling the function to pass the memory address.

*: (Indirection Operator): Used within the function to access and modify the value at the memory address.

Let me know if you'd like any clarification or more examples!

Course Syllabus