Search code examples
c++cpointersfunction-pointersindirection

Intuitively explaining pointers and their significance?


I'm having a hard time understanding pointers, particularly function pointers, and I was hoping someone could give me a rundown of exactly what they are and how they should be used in a program. Code blocks in C++ would be especially appreciated.

Thank you.


Solution

  • The concept of indirection is important to understand.

    Here we are passing by value (note that a local copy is created and operated on, not the original version) via increment(x):

    pass by value

    And here, by pointer (memory address) via increment(&x):

    pass by pointer

    Note that references work similarly to pointers except that the syntax is similar to value copies (obj.member) and that pointers can point to 0 ("null" pointer) whereas references must be pointing to non-zero memory addresses.

    Function pointers, on the other hand, let you dynamically change the behaviour of code at runtime by conveniently passing around and dealing withh functions in the same way you would pass around variables. Functors are often preferred (especially by the STL) since their syntax is cleaner and they let you associate local state with a function instance (read up about callbacks and closures, both are useful computer science concepts). For simple function pointers/callbacks, lambdas are often used (new in C++11) due to their compact and in-place syntax.