When to use the Arrow Operator in C and C++
HTML-код
- Опубликовано: 27 дек 2024
- Patreon ➤ / jacobsorber
Courses ➤ jacobsorber.th...
Website ➤ www.jacobsorbe...
---
When to use the Arrow Operator in C and C++ // The arrow operator is one of our basic tools in C and C++, but beginners often get confused about when to use it, versus the dot operator to access members of structs and classes. So, this quick video breaks it down. Enjoy.
***
Welcome! I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.
About me: I'm a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.
More about me and what I do:
www.jacobsorbe...
people.cs.clem...
persist.cs.clem...
To Support the Channel:
like, subscribe, spread the word
contribute via Patreon --- [ / jacobsorber ]
Source code is also available to Patreon supporters. --- [jsorber-youtub...]
So, basicly the arrow operator is an alternative for (*structname).property, but it's easier to use structname->property
Exactly, it's much simpler and clear that way
Thank you this isnt explained anywhere
Fantastic. this video is precisely what I have been looking for three weeks ago
the arrow operator is literally my favorite, it's just so much fun to use, and it looks pleasing (plus its literally a pointer to a member)
one of the simplest yet best explanation!!
thank you so much this was such a nice and a simple explanation!
In 5 minutes you clarified something that has mystified me for years. Nobody ever explained it as well as you just did!
Thanks. Easy and straightforward.
Excellent tutorial! Very understandable and straight to the point! Many thanks for this!
Video Summary:
if you are working with Objects or class/struct
use dot (.) operator
if you are working with pointers to a class/struct
use Arrow(->) operator because it will save your time
instead of writing
(*p).memberVariable its better to write p->memberVariable.
Nice refresher
Crystal Clear Sir!
Lovely and simple
Great short and pinpointing explanation.
Worth mentioning that if you pptr++ the pointer will be advanced by the size of the structure it points to.
Then what would be the next location acc. to this example? Like we know int is 4 byte but what would the compiler assume for string data type? Would it be the size of name assigned to it, but that may change everytime??
Sorry, if I sound stupid.
@@prasantkumarmahato8034 That depends on what kind of string you are talking about, like a C string or a C++ string. If you are talking about a basic c string (char*), that is just a pointer to the first character in the string and the string ends at a null byte (a byte with all 0's). Incrementing that just moves the pointer to the next character, since it is just a pointer to a character.
The standard C++ string comes from the header, and is part of the Standard Template Library (STL), under the std (Standard) namespace. That is a class (a struct with default private members instead of default public members), and it contains 3 internal members.
1) A pointer (aka address) of the first character.
2) The length (aka number of characters it has)
3) The capacity (the maximum number of characters it needs before fetching new memory to rewrite itself to, upon increasing it's length).
Those 3 members will typically be stored on the stack (though could be on the heap, if you make a pointer to the string and allocate using malloc or new)
The extra string of characters in this is stored elsewhere (that is wherever the internal pointer points to) This will be on the heap (not sure if there is a way to force to be on the stack, but that's besides the point).
There is an operator sizeof, and sizeof this C++ std::string is just the 3 internal members mentioned. When you increment, a pointer to this, it just increases the pointer by that many bytes, so it moves it to just after those 3 members.
Also note, often structs and classes, have extra padding to the there memory, so that there size is a multiple of 4 (or maybe sometimes multiples of 8 in newer 64 bit systems? Or maybe not, I'm not sure). I think there is a way to force this padding not to occur.
@@islandcave8738 Thank you for the detailed explanation, really got to know a lot. Also, I just checked the size of string datatype using sizeof() , it shows 24.
The arrow operator is my favorite. I always tell my students it’s easy to remember when to use it, because it looks like it’s pointing to the structs data member, so the type must be a pointer to the struct. It’s so much clearer to me than the indirection operator.
It was helpful thank you :)
wow, this channel is very developer friendly. The theme all dark by default🤣
In C++ struct and class are interchangeable, if you use struct, all members default to public instead of private. This means you can port C-code, and later add procedures to the data structures, how cool is that?
That’s terrible, it just means that if you’re going to try to port from C++ to C you’re going to have a harder time
I thought a struct is a value type whereas a class is a reference type? I think that’s the case in C# anyway
@@gregoryfenn1462 that's just c#.
@@user-ux2kk5vp7m Why would you do that? You go to C++ to scale up, maybe use an old c-based algorithm for example. If you want to stay in C for low-level drivers, then you leave it. Possibly one of the dumbest responses I have ever seen.
@Yusuf Kazi struct and class are the same things in C++, and they are automatically types (no typedef bs required)
U tried well but I'm not been able to catch up 😅
i thought (*ptrr).age is same as (&p1).age where *ptrr gives the value in it which is adress right?
how can it be p1.age?
This one goes to my "watch later" list.
in c++, you would have smart pointers (shared, unique, weak) that have operations for both the dot and the arrow notations.
is there a situation in C where something similar can happen?
In C pointers are just pointers. Basically if you have "some_type *ptr", "struct some_struct *ptr", etc. you basically have object 8 bytes long on x64 machines that stores address memory to whatever type it will have. Only interesting thing happens when you assign array to pointer - array will 'degrade' (automatically typecasted) to pointer, because arrays basically are pointers with type of "some_type (*)[ ]".
What about arrays and an array of pointers?
tnx brother. but what about ">>"?
thank you
I mean, yea it doesn't matter for age from the perspective of size, but in generally wouldn't be better off if we use some time to think about the data type and use an unsigned integer instead for age as a negative age wouldn't logically impossible and might even spare us some problems in the future? (a function couldn't screw us up which is subtracting or whatsoever) we could even go fancy and use uint8 depending on how many instances we create it could make a small difference :)
just asking as I am learning c right now.
It's my favorite operator.
The fundamental behavior of the arrow operator is relatively simple but where I'm confused is in large projects where the arrow operator is used to reference a member of an object of a class outside of my current scope. The question to me becomes an issue of memory management. My question is "if an arrow operator is used to access a member of an object within a class OUTSIDE of my current scope, do I need to allocate (new) and deallocate (delete) memory?". The reason I ask this question is I have been encountering significant use of the arrow operator and if I'm not seeing allocation/deallocation of memory, or the initialization of the pointer, so does this imply the person writing this code is accessing pointers created in some random undefined place, or what am I missing? I can't tell if I'm missing something conceptually, or what I'm seeing is just years and years of TERRIBLE coding practices!!!
Is it good practice to call class attributes with this->foo or just directly call foo? It can look messy if you use this-> a lot but it can look inconsistent if you don't use it everywhere
great video!! thanks
In Java arrows are used in switch statements and lambda expressions, can arrows in C and C++ be used as well in those cases?
cheers
!!!
First comment!, fellow C programmer, keep It up, nice video !!
Thanks
would be great if you make a video on the other arrows 😁
It really confused me using 'cout
The
@@ronnysherer yes i know that this is the Leftshift Bitwise operator. And i know that the operator is overloaded in use of std::cout. Thats the point^^
When i first dived into C++ i was very confused when i saw 'cout
Thanks for the suggestion. I'll add it to the list.
Embedded programmer here. As you no doubt know, there is another function of the double arrow operator. Shifting bits left or right when performing boolean operations. I use that a lot twiddling bits which is very common with embedded processor programming.
I think your pretty → symbol can confuse somebody in this kind of tutorial :D
It's just a '->' arrow, guys. Your CO
How do I get the arrow as a single character? And will it work with any compiler?
@@avonray9147 You'd have to use a specific font for that. I think he made a video about it once, but I can't remember the name.
Yeah, it's just a font ligature. I actually typed "->" and that's all the compiler sees. The editor, just changes it to a single arrow when it's displayed. (ruclips.net/video/5td9upDbkaU/видео.html)
I love that shirt. Also a question:
Does the arrow operator have any impact on performance? Would the parenthesis and the ugly syntax be faster?
No overhead compared to the ""ugly" way. Just "syntactical sugar" - the generated assembly is the same.
1:35 the decadence. the indulgence. slothful.
But when I need to use a pointer instead of a variable?
Ah, good question. I'll add that to my topic list, and see what I can do in a future video.
There's more then one reason to use a pointer. Here are some of them:
1) You want to update an argument inside a function, and use the updated argument after the function
2) You need a primitive variable that will not always contain a value, alternatively you can you std::optional or boost::optional
3) You have an structure with at least 2 members, but you need this object to sometimes occupy enough space for all it's members, and sometimes you just need it to occupy as little space as possible.
4) You are sharing some variable in different parts of your code, and you don't want to duplicate the entire variable all over the place, taking up more memory (this is really only a concern for objects, not primitive variables).
damn explain man! 🤍
A lot of IDEs and I think even VSCode changes the dot to an arrow automatically.
Eclipse IDE auto converts the dot to an arrow... reasonably reliably.
Great video thank you!
But, in this video one thing isn't clear to me... How old are you, Jacob? 😁
It's one of life's great mysteries...and it's constantly changing. 😂
let me give you an advice. Type at the top of your programs using namespace std; . You can type things without that std::
Thanks. Can You Make Video On Efficient Permutation Of String. Any Best & Fast Algo For Permute String & Numbers.
Maybe. What are you trying to do with the string?
I love how your using C++ in this one. I think everyone should use a C++ compiler and then use whatever features they like. Rather than this C vs C++ "religious cult war" just use whatever tools suit the project. The only real benefit IMO of using a C compiler is that it compiles much faster than a C++ compiler. Don't like classes? Don't use them. Like namespaces? Use them. There is no knife against your throat.
C compiler is also generally smaller and more lightweight, which may come into play in cases of highly constrained systems - typically embedded. That's where the barebones approach of C has an edge over the chunky C++.
@@Alche_mist absolutely. Systems like Sega Genesis has a solid C compiler, but C++ is not possible/practical.
@@Alche_mist This is why a cross-compiler is used for constrained systems. Even on Arduino development happens in C++ by default.
Weird reasoning for -> operator, why don't just use . for pointers too?
You can. You just have to dereference the pointer first. :)
@@MrFedX i mean, from a language design standpoint, there is no reason why -> operator should use different notation than usual . and it just adds more stupid work for you to do when you deside to create a procedure and copy your code to it, and pass variables by a pointer.
What i dont quite understand is why the dot operator wasnt simply overloaded to work with pointers.
Good question. I'm not sure, but I imagine that they were trying to avoid ambiguity. With the arrow operator, you know when you see it that you're working with a pointer. If the dot were overloaded, you would have to remember or go back and check the declaration. That's just my guess.
With how much ambiguity you can conjure in c++ having an overloaded dot operator seemed rather innocent to me. It makes sense with a c mindset i think.
As Jacob said, "clarity".
While the compiler will know whether-or-not the token is a pointer or a variable (like the name of a struct), the (human) reader may not.
Since an array could be 'seen' as a struct with trivial elements:
char str[5]; being like struct { char e0, e1, e2, e3, e4 } st;
you may as well ask why not use the dot to reference into an array: st.e2
One can perform "pointer arithmetic", including incr/decr...
Not allowed if the token is a 'compile time' identifier...
When you have a pointer to struct use -> otherwise use .
Why not double points .. ? The -> seems cumbersome as f...
This is arguably the most unnecessary feature in c++.
No! I find it extremely useful. I can greatly simplify my code when I'm dealing with complex structures.
thanks
Thanks
thanks