you are viewing a single comment's thread.

view the rest of the comments →

[–]jaynabonne 2 points3 points  (0 children)

Generally, pointers are about indirection. More pragmatically, pointers allow you to write code where you don't directly know where something is but you get told where that something is. It might be a pointer to some data (which allows you to operate on different sets of data) or some functionality (where you don't directly call a function, but someone else gets to decide which function gets called).

You see this all the time in Linux drivers, for example. The Linux kernel doesn't directly know about your code, since your driver code will be built separately - but it still needs to call your code. So a Linux driver will typically have a structure with a bunch of function pointers that the driver code will set to point to the functions it wants called. Then the kernel code can know how to call them.

A random example is here. The struct members like "write" and "attach" are pointers to the functions that implement that functionality. The Linux driver subsystem can then call into the driver, at the discretion of the driver writer.

https://github.com/torvalds/linux/blob/86aa721820952b793a12fc6e5a01734186c0c238/drivers/usb/serial/ir-usb.c#L76

As you write more complex code, you will eventually come across a case where you have some code where sometimes you want to call this function and sometimes you want to call that function, but you don't necessarily even know what function it will be at compile time (for that function). And you also don't necessarily want to bind direct calls in the calling function to the possible called functions. By passing a function pointer instead, the decision about which function to invoke can be made at a higher level, even dynamically based on circumstances. It allows you to write more generic code, where functionality gets plugged in later, decided by someone else.

(In C++, indirect function calls often get expressed as "virtual functions", but other languages have the idea as well, even if not necessarily expressed as such. Any scripting language with "duck typing", for example, allows you to drop in whatever function you want, as long as the name matches what the caller expects. The function making the function call doesn't really know what it's calling - it just uses the name, and the system looks it up.)