Pointers in C++
C++ supports pointers, allowing you to pass references to values and objects within your program.
In this example, we demonstrate how pointers work in contrast to values using two functions: zeroval
and zeroptr
.
The zeroval
function takes an int
parameter, so arguments are passed to it by value. This means zeroval
receives a copy of the value, distinct from the one in the calling function.
On the other hand, zeroptr
takes an int*
parameter, which is a pointer to an int
. Inside the function, *iptr
dereferences the pointer, allowing us to modify the value at the memory address it points to.
In the main
function, we create an integer i
and demonstrate the difference between passing by value and passing by pointer:
- We first print the initial value of
i
. - We call
zeroval(i)
, which doesn’t change the value ofi
inmain
. - We then call
zeroptr(&i)
, passing the address ofi
. This changes the value ofi
inmain
because it has a reference to the memory address of the variable. - Finally, we print the memory address of
i
using the address-of operator&
.
When you compile and run this program, you’ll see output similar to this:
This demonstrates that zeroval
doesn’t change the i
in main
, but zeroptr
does because it has a reference to the memory address for that variable.