Pointers in C++

#include <iostream>

// We'll show how pointers work in contrast to values with
// 2 functions: `zeroval` and `zeroptr`. `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
void zeroval(int ival) {
    ival = 0;
}

// `zeroptr` in contrast has an `int*` parameter, meaning
// that it takes an `int` pointer. The `*iptr` code in the
// function body then *dereferences* the pointer from its
// memory address to the current value at that address.
// Assigning a value to a dereferenced pointer changes the
// value at the referenced address.
void zeroptr(int* iptr) {
    *iptr = 0;
}

int main() {
    int i = 1;
    std::cout << "initial: " << i << std::endl;

    zeroval(i);
    std::cout << "zeroval: " << i << std::endl;

    // The `&i` syntax gives the memory address of `i`,
    // i.e. a pointer to `i`.
    zeroptr(&i);
    std::cout << "zeroptr: " << i << std::endl;

    // Pointers can be printed too.
    std::cout << "pointer: " << &i << std::endl;

    return 0;
}

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:

  1. We first print the initial value of i.
  2. We call zeroval(i), which doesn’t change the value of i in main.
  3. We then call zeroptr(&i), passing the address of i. This changes the value of i in main because it has a reference to the memory address of the variable.
  4. 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:

initial: 1
zeroval: 1
zeroptr: 0
pointer: 0x7ffd5e7e70bc

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.