Example 4: Pointers with Functions

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:

  • Modifying variables directly within a function.
  • Passing large data structures efficiently (e.g., arrays).
  • Returning multiple values from a function.

This example demonstrates how pointers can be used to modify values inside a function.


Code Example

#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;
}

Explanation & Output

Code Breakdown:

  1. Defining the swap Function:
    • The function swap(int* a, int* b) takes two integer pointers as parameters.
    • Inside the function:
      • 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.
  2. Calling the Function in main():
    • swap(&num1, &num2); passes the addresses of num1 and num2 to the function.
    • Inside the function, the values are swapped directly in memory, affecting the original variables.

Expected Output:

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++.