In C++, pointers can be used as function arguments to pass data by reference, allowing functions to modify the original variables. Using pointers with functions is useful for:
This example demonstrates how pointers can be used to modify values inside a function.
#include <iostream>
// Function to swap two numbers using pointers
void swap(int* a, int* b) {
int temp = *a; // Dereference to get value
*a = *b; // Swap values
*b = temp;
}
int main() {
int num1 = 10, num2 = 20;
std::cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << std::endl;
// Passing addresses of num1 and num2 to the function
swap(&num1, &num2);
std::cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << std::endl;
return 0;
}
swap
Function:
swap(int* a, int* b)
takes two integer pointers as parameters.temp = *a;
stores the value of a
in temp
.*a = *b;
assigns the value of b
to a
.*b = temp;
assigns the original a
value to b
.main()
:
swap(&num1, &num2);
passes the addresses of num1
and num2
to the function.Before swapping: num1 = 10, num2 = 20
After swapping: num1 = 20, num2 = 10
This example highlights how pointers allow functions to modify variables directly, making them essential for efficient memory management and data manipulation in C++.