In C++, function arguments can be passed as pointers to allow direct modification of the original variables. This is useful in scenarios where:
This example demonstrates how to pass function arguments as pointers to modify the original values.
#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;
}
doubleValue
)doubleValue(int* num)
takes a pointer as an argument.*num *= 2;
→ Dereferencing num
allows modifying the actual value stored at that memory address.main()
doubleValue(&value);
→ Passes the address of value
to the function.value
directly in memory, doubling its value.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++.