A Classic Example: Swap
Part of the Logic & Flow section of Coddy's C journey — lesson 28 of 63.
The swap function is one of the most famous examples that demonstrates why pointers are essential in C programming. The goal is simple: write a function that exchanges the values of two variables. However, this seemingly straightforward task reveals a fundamental limitation of pass-by-value.
Consider what happens if you try to swap two variables using regular pass-by-value:
void badSwap(int a, int b) {
int temp = a;
a = b;
b = temp;
// This only swaps the copies, not the original variables!
}This approach fails because the function only receives copies of the values. The original variables in the calling function remain unchanged.
The solution requires passing pointers to the variables instead:
void swap(int *a, int *b) {
int temp = *a; // Store the value at address a
*a = *b; // Put the value from address b into address a
*b = temp; // Put the stored value into address b
}By passing the addresses of the variables and using the dereference operator, the function can directly modify the original variables' values. This makes the swap function a perfect demonstration of when and why you need pointers to accomplish tasks that pass-by-value simply cannot handle.
Challenge
EasyWrite a C program that implements and demonstrates the classic swap function using pointers. Your program should:
- Create a function named
swapthat takes two pointers to integers as parameters - Inside the
swapfunction, exchange the values at the memory addresses pointed to by the two pointers using a temporary variable - In the
mainfunction, read two integers from the user input - Print the original values in the format:
Before swap: a = [value], b = [value] - Call the
swapfunction and pass the addresses of both variables using the address-of operator - After the function call, print the swapped values in the format:
After swap: a = [value], b = [value]
Your output should demonstrate that the function successfully exchanges the values of the original variables:
Before swap: a = [first_input], b = [second_input]
After swap: a = [second_input], b = [first_input]This challenge demonstrates why pointers are essential for the swap operation - the function must access the original variables' memory locations to permanently exchange their values, which is impossible with pass-by-value.
Cheat sheet
The swap function demonstrates why pointers are essential in C. Pass-by-value cannot swap original variables because functions only receive copies:
void badSwap(int a, int b) {
int temp = a;
a = b;
b = temp;
// This only swaps the copies, not the original variables!
}The correct approach uses pointers to access and modify the original variables:
void swap(int *a, int *b) {
int temp = *a; // Store the value at address a
*a = *b; // Put the value from address b into address a
*b = temp; // Put the stored value into address b
}By passing addresses and using the dereference operator (*), the function can directly modify the original variables' values.
Try it yourself
#include <stdio.h>
// TODO: Write your swap function here
int main() {
int a, b;
// Read input
scanf("%d", &a);
scanf("%d", &b);
// Print original values
printf("Before swap: a = %d, b = %d\n", a, b);
// TODO: Call your swap function here
// Print swapped values
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions