Hello! Welcome to the final lesson of our module on Pointers and Functions.
In our last lesson, we saw how to use pointer parameters as "output parameters" to allow a function to return multiple values. This technique works because passing a pointer gives the function direct access to modify a variable in the caller's scope.
Today, we'll solidify this crucial concept by implementing one of the most fundamental utility functions in C: a function to swap the values of two variables. This simple task is a perfect case study that demonstrates why understanding the distinction between pass-by-value and pass-by-reference is not just academic, but essential for writing correct and effective C code.
The Challenge: Modifying the Caller's Variables
Let's say we have two integer variables in main, a and b, and we want to write a function swap to exchange their values. A programmer new to C might first attempt this:
#include <stdio.h>
void swap_fail(int x, int y) {
int temp = x;
x = y;
y = temp;
printf("Inside swap_fail: x = %d, y = %d\n", x, y); // Values will be swapped here
}
int main() {
int a = 10;
int b = 20;
printf("Before swap: a = %d, b = %d\n", a, b);
swap_fail(a, b);
printf("After swap: a = %d, b = %d\n", a, b); // But will they be swapped here?
return 0;
}
What do you think the final output for a and b will be? The answer reveals the core nature of how C passes arguments to functions.
Why Pass-by-Value Fails for Swapping
The swap_fail function above will not work as intended. The values of a and b in main will remain unchanged. This is because C, by default, uses pass-by-value. When swap_fail(a, b) is called, the values of a and b are copied into new, separate local variables x and y within the swap_fail function's stack frame. The function successfully swaps its local copies, but these are destroyed when the function returns, having no effect on the original a and b in main.
The following video provides an excellent explanation of this process, visualizing the function call stack and making the distinction between local variables clear.
Pointers as function arguments - call by reference
This video from mycodeschool explains exactly why a function using pass-by-value cannot modify its caller's variables. It uses memory diagrams to show how separate stack frames are created for each function call, isolating their local variables.
Watch the segments from 00:41 to 02:58 and 04:21 to 11:02. The first part introduces the problem with a simple increment function. The second part provides a detailed look at the C memory model (stack, heap, etc.) and how function call stacks work, which is key to understanding why the local variables are distinct.
The Solution: Pass-by-Reference Using Pointers
As you've likely deduced, to modify a and b from within a function, we must pass their memory addresses. The function will accept these addresses into pointer variables. By dereferencing these pointers, the function can reach back into the caller's stack frame and manipulate the original variables. This mechanism is known as pass-by-reference.
Here is what the correct swap function looks like:
void swap(int *ptr_a, int *ptr_b) {
int temp = *ptr_a; // Get the value at the address ptr_a points to
*ptr_a = *ptr_b; // Set the value at ptr_a's address to the value at ptr_b's address
*ptr_b = temp; // Set the value at ptr_b's address to the stored temp value
}
To use it, the caller must pass the addresses of the variables: swap(&a, &b);.

Let's watch two short videos that walk through the implementation and then read a textual summary.
Pointers as function arguments - call by reference
First, let's return to the mycodeschool video, which now presents the pointer-based solution to the problem it introduced earlier. This provides a direct contrast between the failed and successful approaches.
Watch the segment from 11:02 to 13:44. It shows how passing the address of the variable and using a pointer parameter allows the function to modify the original value.
C Program To Swap Two Numbers using Pointers
Now, let's see a practical coding demonstration. This video from Technotip builds a complete C program to swap two numbers using a pointer-based function from start to finish.
Watch the entire video. Notice the clear distinction between passing the addresses (&a, &b) in the function call and declaring the parameters as pointers (int *x, int *y) in the function definition.
For a solid reference, the following article provides the C code and a clear explanation of how the pointer-based swap works.
Custom Swap Function for Swapping two Numbers in C
This article from Unstop provides a concise textual explanation and a complete code example of the custom swap function.
Read the section 'Custom Swap Function for Swapping two Numbers in C'. Focus on the code example and the step-by-step explanation that follows it. This will reinforce what you saw in the videos.
The swap function is a building block in many algorithms, especially sorting algorithms like bubble sort or quicksort, where elements in an array must be exchanged in-place for efficiency. In your work with AUTOSAR and embedded systems, where performance and direct memory manipulation are critical, this pattern of modifying data in-place via pointers is ubiquitous.
Test your understanding!
Let's extend the swap concept. Write a C function rotate_values that takes pointers to three integer variables (a, b, and c) and rotates their values. The value of a should move to b, b to c, and c back to a.
- Write the complete
rotate_valuesfunction. - Show how you would call this function from
mainto rotate three integersv1,v2, andv3.
Show answer
-
rotate_valuesFunction Implementation:Just like with a two-variable swap, we need a temporary variable to hold one of the original values to prevent it from being overwritten.
void rotate_values(int *p_a, int *p_b, int *p_c) { // Store the original value of 'a' before it's overwritten int temp = *p_a; // a's location gets c's value *p_a = *p_c; // c's location gets b's value *p_c = *p_b; // b's location gets the original value of a (stored in temp) *p_b = temp; }Note: There are other valid sequences, e.g., storing
c's value first. The key is to save one value before its location is overwritten. -
Calling from
main:#include <stdio.h> // ... (paste rotate_values function here) ... int main() { int v1 = 10, v2 = 20, v3 = 30; printf("Before rotate: v1=%d, v2=%d, v3=%d\n", v1, v2, v3); // Pass the addresses of the variables to the function rotate_values(&v1, &v2, &v3); printf("After rotate: v1=%d, v2=%d, v3=%d\n", v1, v2, v3); // Expected output: After rotate: v1=30, v2=10, v3=20 return 0; }
Conclusion
This lesson concludes our module on the fundamental interactions between pointers and functions. The seemingly simple swap function perfectly encapsulates why these concepts are so deeply intertwined.
Key Takeaways:
- C uses pass-by-value, meaning functions receive copies of arguments. This prevents a function from directly modifying its caller's variables.
- To modify a caller's variables, you must simulate pass-by-reference by explicitly passing pointers (memory addresses) to them.
- The
swaputility function is the classic example of this requirement: you must pass pointers to the variables you intend to swap. The function then uses the dereference operator (*) to access and change the values at those original addresses.
This marks a significant point in your journey. You now have a solid command of how pointers work with variables and functions that reside on the stack.
Preview of the Next Module:
In our next module, Dynamic Memory Management, we will shift our focus from the stack to the heap. You'll learn how to request, use, and release memory at runtime using malloc(), calloc(), realloc(), and free(). This will unlock the ability to create data structures, like dynamic arrays and linked lists, whose size is not known when you compile your program—a critical skill for any advanced C programmer.