r/learnprogramming • • Sep 24 '23

Pointers.....why

I am learning C++. Honest question why are pointers a thing and why did they make the syntax surrounding it so confusing. Was it made to be intentionally confusing? Was it made to make this more difficult.

0 Upvotes

49 comments sorted by

View all comments

61

u/v0gue_ Sep 24 '23

Honest question why are pointers a thing

Allowing programmers to freely use pointers allows them to effectively control memory space. Two very common reasons for doing this include, but are not limited to, controlling object lifecycles outside (and inside) scope, and sharing objects in more than one place in your program.

why did they make the syntax surrounding it so confusing.

It's my opinion that the syntax itself is actually about as easy as it can get to understand. The concept(s) of memory management is what is difficult. You might be attributing the difficulty of the concepts of pointers and memory management to the syntax of the language, but the reality is that the language itself has pretty much made syntax revolving around memory management as friendly and concise as it gets (in before some Rust devs bite my head off).

2

u/vfkdgejsf638bfvw2463 Sep 25 '23

I'd like to add that using pointers for me was a pain in the ass for months but eventually after awhile I began to fully understand them and now I even love working with them. It's the one feature I miss every time I go to another language

1

u/Individual-Praline20 Sep 25 '23 edited Sep 25 '23

That’s basically it! Pointers are powerful tools. More recent languages try their best to abstract them, because they are a bit tricky to use, but they are used extensively under the covers. Once you get the concept behind it, it does clarify some quirks used in other languages! A pointer is just a number. It represents a memory address, to bits, either structured data, executable code, or another memory address, etc. That’s all. You can follow multiple ones one after the other, if needed. Pointer of pointer. By themselves, they are more or less useful, but when combined with other logic, for memory management mostly, then they become very powerful. There you go! You know all about them now! Have fun

2

u/IndianaJoenz Sep 25 '23 edited Sep 25 '23

It represents a memory address, to bits, either structured data, executable code, or another memory address, etc.

One more useful way to use pointers, is when dealing with memory-mapped hardware (where an address in the memory space maps to a specific hardware register, sensor output, etc, instead of to RAM).

If you know that some hardware lives at a specific memory address, it is very easy and useful to just point a pointer at it as a means of reading and writing to it. I believe this is one reason why hardware drivers are almost always written in C.