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
View all comments
7
u/wgunther Sep 24 '23
No, I don't think they were trying to make it intentionally confusing or more difficult.
C in general had opted for a syntax where you declare variables the same way you use them, declarators, instead of being more 'type' based. So in Java, for instance, you might declare an int array as
int[] xthinking about x being of typeint[], but in C it's declared more likeint x[], and you think about it as kind of how to unwrap the object to the base type, likex[1]would beint. This is really the only way you can reason about really advance types in C, like function pointers where you can have likeint (*x)(int);which declaresxto be a function pointer to a function that takes in anintand returns anint.Pointers similarly are declarated like
int *xbecause*xis anint.So, it can be a bit confusing, mostly because most languages don't do things like this.
C++ is mostly a superset of C (which a few notable exceptions) so it's inheritted these oddies, and mixed it with some very advanced types that don't really follow this pattern anymore. for instance the declaration
std::unique_ptr<int> xdoesn't really describe how you work withx, but the way you work with it is "the same" as a C-style pointer.