Example 5: Pass Function Arguments as Pointers

In C++, function arguments can be passed as pointers to allow direct modification of the original variables. This is useful in scenarios where:

  1. Modifying values in a function (e.g., swapping values, updating data).
  2. Passing large structures efficiently without making copies (e.g., arrays, objects).
  3. Returning multiple values from a function without using return statements.

This example demonstrates how to pass function arguments as pointers to modify the original values.


Code Example

#include <iostream>

// Function to double the value of an integer using a pointer
void doubleValue(int* num) {
    *num *= 2;  // Dereferencing the pointer to modify the actual value
}

int main() {
    int value = 10;

    std::cout << "Before function call: value = " << value << std::endl;

    // Passing the address of value to the function
    doubleValue(&value);

    std::cout << "After function call: value = " << value << std::endl;

    return 0;
}

Explanation & Output

Code Breakdown:

  1. Defining the Function (doubleValue)
    • The function doubleValue(int* num) takes a pointer as an argument.
    • Inside the function:
      • *num *= 2; → Dereferencing num allows modifying the actual value stored at that memory address.
  2. Calling the Function in main()
    • doubleValue(&value); → Passes the address of value to the function.
    • The function modifies value directly in memory, doubling its value.

Expected Output:

Before function call: value = 10
After function call: value = 20

This example shows how passing function arguments as pointers allows direct modification of variables, making it an efficient way to handle data in C++.