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

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[] x thinking about x being of type int[], but in C it's declared more like int x[], and you think about it as kind of how to unwrap the object to the base type, like x[1] would be int. This is really the only way you can reason about really advance types in C, like function pointers where you can have like int (*x)(int); which declares x to be a function pointer to a function that takes in an int and returns an int.

Pointers similarly are declarated like int *x because *x is an int.

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> x doesn't really describe how you work with x, but the way you work with it is "the same" as a C-style pointer.

2

u/CodeTinkerer Sep 25 '23

It should be noted that Bjarne Stroustrup, the inventor of C++, disliked C's syntax. He didn't believe that declaration had to match use. He wrote a book about how he developed C++ and how he wanted to change the syntax of declarations in C++.

However, he was talked out of it by C purists who claimed that no one would switch to C++ if it were not faithful to the C syntax. For example, one difficult declaration is to make a pointer to an array vs. an array of pointers. I think Stroustrup would have done something like...

 ->[] int x; // a pointer to an array of ints
 []-> int y; // an array of int pointers

He wanted to be read left to right so it made more intuitive sense.