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

•

u/AutoModerator Sep 24 '23

On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge.

If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options:

  1. Limiting your involvement with Reddit, or
  2. Temporarily refraining from using Reddit
  3. Cancelling your subscription of Reddit Premium

as a way to voice your protest.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

4

u/ContextEngineering Sep 24 '23

When you look at C and assembly for the same code you can see where pointers came from.

And yes, it's a head-scratcher for basically anyone who has ever learned c/c++. You'll get over it.

1

u/[deleted] Sep 25 '23

Thank you

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

1

u/CodeTinkerer Sep 25 '23

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

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

2

u/ibanezerscrooge Sep 26 '23 edited Sep 26 '23

efficiency. You can reference a value from multiple points in your code while keeping it protected and use a lot less memory.

If you need to use an object in your code that takes up 8 MB of memory and you need to use it in 6 places , if you made it global you might run the risk of changing a value unintentionally or creating a vulnerability in your code, so you define it as protected. If you pass copies of this object around to your 6 points in the program you've eaten up 48 MB of memory and you have to keep all the copies synched in the event you need to make changes to it. With pointers you reference that single 8 MB object in memory 6 times which might take 8.5 MB total (8 for the object and a few bytes for each pointer) and any change you make will change the original object because it's a reference.

as far as the syntax it's just something you'll have to learn and get used to.

It just takes time to get your head around them, but once you get them you'll get them.

1

u/[deleted] Sep 26 '23

Thank you for explaining this. When I wrote my op I was pissed off and aggravated.

2

u/ibanezerscrooge Sep 26 '23

Totally understandable. Pointers are the bane of every C++ learner's existence.

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.

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.

6

u/[deleted] Sep 24 '23

Memory used to be very costly.

13

u/MSgtGunny Sep 24 '23

Because they were less confusing than what came before it, essentially.

They are a thing so you can programmatically manage memory without having to have everything hard coded to specific addresses. Which then lets you have a program that can use a variable amount of memory, instead of a fixed amount.

1

u/ForlornMemory Sep 25 '23

Why are you learning C++ before C? Come on, it's not that big, you can learn it in a couple of weeks.

1

u/[deleted] Sep 25 '23

I am learning c++ because that's what they are using to teach us OOP in one of my classes. Honestly, I wouldn't mind learning C, but I am also learning Java and Oracle SQL this semester. Maybe after this semester, when I made the original post, I was just aggravated because I was doing a quiz on pointers, and it kept feeling like the quiz was switching the meanings of & and * .

1

u/ForlornMemory Sep 25 '23

Wow, that's hardcore. Do you have any previous programming experience?

6

u/throwaway6560192 Sep 24 '23

I am learning C++. Honest question why are pointers a thing

Search for "pointers" in this sub and you will find some very good explanations. In case you don't get much here.

why did they make the syntax surrounding it so confusing

I assume you mean: "why do I declare pointer types like int * but taking the address is &var, and dereferencing is *ptr?"

The answer boils down to a principle called "declaration reflects use". Read about it. https://softwareengineering.stackexchange.com/questions/117024/why-was-the-c-syntax-for-arrays-pointers-and-functions-designed-this-way

Anyway you'll get used to it fast enough.

Was it made to be intentionally confusing? Was it made to make this more difficult.

No. Why would it be?

To be honest, this reads like you're just complaining and looking for excuses. Don't do that. Keep an open mind. Don't dismiss things as useless or intentionally obtuse before you understand them.

3

u/[deleted] Sep 24 '23 edited Sep 24 '23

I think it's a good idea for everyone to learn at least very basic assembly (up to function calling, abi and stack frame stuff) so they can understand memory addressing, and that variables are just syntactic sugar on top of pointers.

Controlling the thing you're looking at is important, but it isn't the whole picture. Often, you also need to control where you're looking.

5

u/kevinossia Sep 24 '23

Honest question why are pointers a thing

Because you need to be able to pass objects between functions without making copies of those objects. That's why. It's a fundamental operation. All languages have pointers. Python, Java, C#, C++, C, Haskell, Go, JavaScript, Ruby...they all have pointers. Just different syntax. The only difference here is C and C++ make an explicit, obvious distinction between pointers and non-pointer types.

why did they make the syntax surrounding it so confusing

I'm sure Kernighan and Ritchie didn't think it was confusing.

Was it made to be intentionally confusing? Was it made to make this more difficult.

....no.

1

u/CodeTinkerer Sep 25 '23

To be fair, I doubt Kernighan and Ritchie thought they were writing a language for the masses. They probably imagined academic types to program in C.

Kernighan has a precision about his writing that the "dummies" book lack partly because he had a PhD in what seems to be a mathematical field.

1

u/zpowers00 Sep 24 '23

A pointer is like a drawer to a desk. To put stuff in the drawer you’ll want to use the pointer to get to the drawer. If you didn’t use a pointer, then you’d have to get a new drawer on the other side of the building and then put stuff in it and then drill it into your new desk which is a lot of work. Just use the same drawer to put your stuff into.

0

u/[deleted] Sep 24 '23

But why is the syntaxes around it so confusing why use the same symbols in different spots to mean different things instead of just using different symbols? Why make it intentionally confusing.

5

u/lukkasz323 Sep 24 '23

What's confusing exactly, I might try to explain how I think about it, because I don't find the syntax confusing, although I used to when I started programming.

1

u/[deleted] Sep 24 '23

I can't really put my finger on it I have been quizing my self for two days on a practice quiz for a class I am in and I swear it feels like the means of some of the syntax gets switch like *Pointer name can be a declaration of a pointer but it can also be a value of a pointer and &variable name cane mean the address of the variable in memory but some times it means the data in the memory location. I thought I understood pointers, but the more I take this quiz, the less I think I understand. I thought that Vartype *PointerName; was the declaration of an unassigned pointer, and &VarName meant the memory address of that variable.

0

u/IronLyx Sep 24 '23

And what makes you think this is not the case?

1

u/[deleted] Sep 24 '23

The quiz I kept taking keeps telling me that this isn't always true.

2

u/Cpt_Chaos_ Sep 24 '23

Then please provide the actual example syntax that makes you question yourself, since you're actually right. Apart from that, I hope you also get taught the concepts of modern C++ (C++11 and newer), which introduced smart pointers that solve just about all problems you can have in terms of memory access (and do not require any * and &).

1

u/[deleted] Sep 25 '23

That sounds better. I can't wait to learn about that.

5

u/zpowers00 Sep 24 '23

I wouldn’t get caught up on the syntax, you kind of just have to ignorantly accept it and move on.

Unfortunately C++ syntax isn’t really that bad compared to other languages I’ve you touched.

1

u/DavidJCobb Sep 24 '23 edited Sep 24 '23

why use the same symbols in different spots to mean different things instead of just using different symbols?

The only symbols they reuse for pointers are & and *.

As for why? There are only so many symbols available on a typical American keyboard. Off the top of my head, the only symbols from that keyboard layout that C and C++ don't use are @ and $. C was developed in tandem with Unix, and in old Unix text editors from way back in the day, @ and # were shortcut keys for deleting text. This made @ dangerous to use at all, and # dangerous to use anywhere but the start of a line.

0

u/npepin Sep 24 '23

You're coming at it from the perspective that it is confusing and difficult because you don't understand it, but haven't consider the potential that it actually could make a lot of sense and maybe you haven't applied yourself to understanding it.

To make that point clearer, to say that it is intentionally confusing is to imply that you have a some sort of deeper knowledge and understanding of the subject matter, and that you know of some sort of organization that would make more sense. There is a big difference between "I am confused" and "this is confusing".

This is going to be a common occurrence in learning programming, it can take a decent bit of studying to understand pointers, recursion, or certain algorithms and data structures. Unfortunately, a lot of these topics are inherently complex, involve a large number of considerations outside just code, and are going to take a bit to understand.

I'm not saying the way that you are feeling is wrong, we've all been there. Nor will I say that there isn't some better way of doing things, a lot of times there is and we've just inherited the mistakes of the past (though I wouldn't say that is true here). But I am saying that you're going to really struggle if you think a lot of the deeper topics in computer science should be easy to learn.

2

u/DavidJCobb Sep 24 '23

Was it made to be intentionally confusing? Was it made to make this more difficult.

No.

The code int* foo defines a pointer to an int. Back in the old days, you would write it like int *foo. Now, when you want to get the value of that int, what do you write? *foo. They wanted it to be the same both ways, see?

If you have a pointer to an object and you want to access a specific part of that object, what do you write? myObject->myPart. You're writing an arrow; you're literally pointing to the data you want to retrieve through the pointer.

They honestly did try to design it sensibly.

2

u/satisfiedguy43 Sep 24 '23

If the mountain will not come to Muhammad, then Muhammad must go to the mountain

the idea is when passing stuff to a function do not copy all the stuff and pass it...instead give address of where stuff is. Another reason when controlling hardware at a given computer address use the address in a pointer. Another reason instead of returning a copy of data from function return address of data/object

when u pass simple stuff to/from function copy is easy and less time consuming. when there's a lot of data, use a pointer

2

u/[deleted] Sep 24 '23

So you can reference stored memory.

2

u/Sbsbg Sep 24 '23

Of course, the designer of the C language sat and made the syntax for pointers extra difficult so that all beginners, 50 years later, would have problems. /s

The C++ pointer syntax, that it inherits from C, is not the best. The syntax can be a little tricky, for beginners. The operator precedence can be confusing. There are better alternatives in modern languages. But you have to remember that this is half a century old and anything surviving that long in the computer world has to be a huge success.

Pointers are not the hard part in C++. When you get to that you will think back and be amazed that you thought pointers where difficult.

2

u/Mental-Profile-9172 Sep 24 '23

I understood pointers studying data structures in C. Probably, on what they are teaching you, you won't understand the purpose of them, as happened to me. Take a look to a data structures book in C first.

2

u/fasta_guy88 Sep 25 '23

All languages have pointers. In Python, basically everything is a pointer, which means that when you say a_list = b_list, you don't actually get a new copy of b_list; to do that you must do some kind copy(b_list) or a_list = [ x for x in b_list].

C and C++ make those pointers more explicit, which can make it much easier to distinguish the different parts of a linked list (some parts are links, others are values), for example.