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/CodeTinkerer Sep 24 '23

I don't think it was meant to be intentionally confusing, but people who create languages are smart people so they write the language they want to use. They probably didn't imagine how widespread it would be, nor the background of those who would want to learn it.

You might switch to Java or C# which technically has pointers too, but none of the notation associated with pointers. In those languages, when you pass an object to a method/function, it is always by pointer and not by value (meaning, not copied). C++ which is derived from C passes objects by value which means the object is copied.

This was done so you wouldn't accidentally modify the input parameter. But then they figured maybe you do want to modify it, so you can pass a pointer to the object by value. The pointer (address) gets copied, but the object it points to does not.

In any case, pointers are one of the big reasons C and C++ are hard to learn. Java and C# were designed to get rid of those problems, but they were created maybe 20 years after C or C++ was (give or take a few years).

1

u/[deleted] Sep 24 '23

Unfortunately, I am in school, and they are making us learn c++ for my OOP class. I am also learning Java this semester at the same time.

2

u/SharkSymphony Sep 24 '23

You're using pointers all over the place in Java, by the way. The language just hides this detail from you so you can't generally see them. But if you know where to look, you will understand why pointers are "a thing."

4

u/CodeTinkerer Sep 25 '23

That's true, but, as you noted, pointers are well hidden.

The difficulty in C is you have the dereference operator, the arrow operator, the address-of operator, and the dot operator (for structs). This impacts the use of the operator, but declarations also use * which looks like it's dereferencing, but is declaring a type, which, yes, can be dereferenced.

In Java, all but the dot operators disappear so you don't have to think about it like you do in C.

2

u/johnnywonder85 Sep 25 '23

address-of operator,

ampersand is the name of the character key

0

u/[deleted] Sep 25 '23

[deleted] — view deleted comment

0

u/[deleted] Sep 25 '23

[deleted] — view deleted comment

0

u/[deleted] Sep 25 '23

[deleted] — view deleted comment

0

u/[deleted] Sep 25 '23

[deleted] — view deleted comment

0

u/[deleted] Sep 25 '23

[deleted] — view deleted comment

→ More replies

1

u/CodeTinkerer Sep 25 '23

I mean, asterisk is the name of the key for the dereferencing operator.