Cpp Passing Pointers To Functions
## C++ Passing Pointers to Functions
In C++, you can pass pointers as arguments to functions. This technique is highly useful because it allows a function to modify the actual variable in the calling scope (pass-by-pointer) and enables efficient passing of large data structures, such as arrays or objects, without copying their entire contents.
---
## Syntax and Usage
To pass a pointer to a function, you simply declare the function's parameter as a pointer type.
```cpp
// Function declaration accepting a pointer to an integer
void modifyValue(int *ptr);
```
When calling the function, you pass the address of the variable using the address-of operator (`&`), or pass an existing pointer variable directly.
```cpp
int number = 42;
modifyValue(&number); // Passing the address of 'number'
```
Inside the function, you dereference the pointer using the asterisk (`*`) operator to read or modify the value stored at that memory address.
---
## Code Examples
### Example 1: Modifying a Variable Inside a Function
The following example demonstrates how to pass a pointer to an `unsigned long` variable to a function. The function updates the variable's value with the current system time.
```cpp
#include
#include
using namespace std;
// Function declaration (prototype)
void getSeconds(unsigned long *par);
int main()
{
unsigned long sec;
// Pass the address of 'sec' to the function
getSeconds(&sec);
// Output the modified value
cout << "Number of seconds: " << sec << endl;
return 0;
}
// Function definition
void getSeconds(unsigned long *par)
{
// Dereference the pointer to assign the current epoch time
*par = time(NULL);
return;
}
```
**Output:**
```text
Number of seconds: 1698274045
```
---
### Example 2: Passing Arrays to Functions Using Pointers
In C++, an array name decays to a pointer pointing to its first element. Therefore, a function that accepts a pointer can also accept an array.
The following example passes an array of integers to a function using a pointer, along with the size of the array, to calculate the average value.
```cpp
#include
using namespace std;
// Function declaration accepting a pointer to int and the array size
double getAverage(int *arr, int size);
int main()
{
// An integer array with 5 elements
int balance = {1000, 2, 3, 17, 50};
double avg;
// Pass the array (which decays to a pointer to the first element)
avg = getAverage(balance, 5);
// Output the returned average
cout << "Average value is: " << avg << endl;
return 0;
}
// Function definition
double getAverage(int *arr, int size)
{
int sum = 0;
double avg;
for (int i = 0; i < size; ++i)
{
// Access array elements using pointer indexing notation
sum += arr;
}
avg = double(sum) / size;
return avg;
}
```
**Output:**
```text
Average value is: 214.4
```
---
## Key Considerations
When passing pointers to functions, keep the following best practices in mind:
1. **Null Pointer Checks:** Always ensure that the pointer passed to a function is not `nullptr` before dereferencing it. Dereferencing a null pointer leads to undefined behavior (typically a segmentation fault).
```cpp
void safeModify(int *ptr) {
if (ptr != nullptr) {
*ptr = 100;
}
}
```
2. **Use `const` for Read-Only Pointers:** If the function only needs to read the value but not modify it, declare the parameter as a pointer to a constant (`const T*`). This prevents accidental modifications and improves code safety.
```cpp
void printValue(const int *ptr) {
// *ptr = 10; // Compiler error: assignment of read-only location
cout << *ptr << endl;
}
```
3. **Pointers vs. References:** In modern C++, passing by reference (`void func(int &ref)`) is often preferred over passing by pointer because it provides cleaner syntax and guarantees that the reference is bound to a valid object (it cannot be null). Use pointers when you explicitly need to handle null states or perform pointer arithmetic.
YouTip