When to use the Arrow Operator in C and C++

  Рет қаралды 37,803

Jacob Sorber

Jacob Sorber

Күн бұрын

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...]

Пікірлер: 103
@georgecop9538
@georgecop9538 2 жыл бұрын
So, basicly the arrow operator is an alternative for (*structname).property, but it's easier to use structname->property
@whymyruffles
@whymyruffles 2 жыл бұрын
Exactly, it's much simpler and clear that way
@jeanmahe8657
@jeanmahe8657 Жыл бұрын
Thank you this isnt explained anywhere
@ZachBradyisBrachZady
@ZachBradyisBrachZady 2 жыл бұрын
Fantastic. this video is precisely what I have been looking for three weeks ago
@whamer100
@whamer100 2 жыл бұрын
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)
@raiyousaf8841
@raiyousaf8841 Жыл бұрын
one of the simplest yet best explanation!!
@leythecg
@leythecg Жыл бұрын
Excellent tutorial! Very understandable and straight to the point! Many thanks for this!
@GAMarine137
@GAMarine137 21 күн бұрын
Nice refresher
@imtiazsabree6562
@imtiazsabree6562 Жыл бұрын
Thanks. Easy and straightforward.
@sheikhmuhammedtadeeb5677
@sheikhmuhammedtadeeb5677 2 жыл бұрын
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.
@ronnysherer
@ronnysherer 2 жыл бұрын
Great short and pinpointing explanation.
@Recovered
@Recovered 2 жыл бұрын
In 5 minutes you clarified something that has mystified me for years. Nobody ever explained it as well as you just did!
@hafizsakib2734
@hafizsakib2734 Жыл бұрын
Crystal Clear Sir!
@michaelacodes
@michaelacodes Жыл бұрын
thank you
@christopherbarrett9900
@christopherbarrett9900 2 жыл бұрын
Thanks
@siddharthasarmah9266
@siddharthasarmah9266 2 жыл бұрын
great video!! thanks
@TheVertical92
@TheVertical92 2 жыл бұрын
would be great if you make a video on the other arrows 😁 It really confused me using 'cout
@ronnysherer
@ronnysherer 2 жыл бұрын
The
@TheVertical92
@TheVertical92 2 жыл бұрын
@@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
@JacobSorber
@JacobSorber 2 жыл бұрын
Thanks for the suggestion. I'll add it to the list.
@pzftw
@pzftw 2 жыл бұрын
Worth mentioning that if you pptr++ the pointer will be advanced by the size of the structure it points to.
@prasantkumarmahato8034
@prasantkumarmahato8034 2 жыл бұрын
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.
@islandcave8738
@islandcave8738 2 жыл бұрын
@@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.
@prasantkumarmahato8034
@prasantkumarmahato8034 2 жыл бұрын
@@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.
@ajklerakos7170
@ajklerakos7170 Жыл бұрын
It was helpful thank you :)
@benjaminshinar9509
@benjaminshinar9509 2 жыл бұрын
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?
@rogo7330
@rogo7330 2 жыл бұрын
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 (*)[ ]".
@zulfazlihamjah8897
@zulfazlihamjah8897 Жыл бұрын
wow, this channel is very developer friendly. The theme all dark by default🤣
@johnsknows3135
@johnsknows3135 Жыл бұрын
cheers !!!
@rogo7330
@rogo7330 2 жыл бұрын
I think your pretty → symbol can confuse somebody in this kind of tutorial :D It's just a '->' arrow, guys. Your CO
@avonray9147
@avonray9147 2 жыл бұрын
How do I get the arrow as a single character? And will it work with any compiler?
@robbieman6265
@robbieman6265 2 жыл бұрын
@@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.
@JacobSorber
@JacobSorber 2 жыл бұрын
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. (kzbin.info/www/bejne/a6XHaqimeceel7c)
@elalemanpaisa
@elalemanpaisa Күн бұрын
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.
@jp5000able
@jp5000able 2 жыл бұрын
It's my favorite operator.
@vallurisonali7269
@vallurisonali7269 Жыл бұрын
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?
@cprogramming5640
@cprogramming5640 2 жыл бұрын
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.
@md.mohiulislam6516
@md.mohiulislam6516 2 жыл бұрын
tnx brother. but what about ">>"?
@andydelle4509
@andydelle4509 2 жыл бұрын
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.
@simonlaflamme8840
@simonlaflamme8840 Ай бұрын
What about arrays and an array of pointers?
@glee21012
@glee21012 2 жыл бұрын
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?
@user-ux2kk5vp7m
@user-ux2kk5vp7m 2 жыл бұрын
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
@gregoryfenn1462
@gregoryfenn1462 2 жыл бұрын
I thought a struct is a value type whereas a class is a reference type? I think that’s the case in C# anyway
@rastaarmando7058
@rastaarmando7058 2 жыл бұрын
@@gregoryfenn1462 that's just c#.
@glee21012
@glee21012 2 жыл бұрын
@@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.
@glee21012
@glee21012 2 жыл бұрын
@Yusuf Kazi struct and class are the same things in C++, and they are automatically types (no typedef bs required)
@duxoakende
@duxoakende 2 жыл бұрын
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
@yousefsadeek6640
@yousefsadeek6640 2 жыл бұрын
damn explain man! 🤍
@judedavis92
@judedavis92 2 жыл бұрын
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?
@johanngerell
@johanngerell 2 жыл бұрын
No overhead compared to the ""ugly" way. Just "syntactical sugar" - the generated assembly is the same.
@Vulto166
@Vulto166 2 жыл бұрын
This one goes to my "watch later" list.
@electromatic2014
@electromatic2014 2 жыл бұрын
First comment!, fellow C programmer, keep It up, nice video !!
@Earth-Worm-Tim
@Earth-Worm-Tim 2 жыл бұрын
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!!!
@smrtfasizmu6161
@smrtfasizmu6161 2 жыл бұрын
In Java arrows are used in switch statements and lambda expressions, can arrows in C and C++ be used as well in those cases?
@limit1586
@limit1586 4 ай бұрын
let me give you an advice. Type at the top of your programs using namespace std; . You can type things without that std::
@giovannibianchessi1578
@giovannibianchessi1578 2 жыл бұрын
Great video thank you! But, in this video one thing isn't clear to me... How old are you, Jacob? 😁
@JacobSorber
@JacobSorber 2 жыл бұрын
It's one of life's great mysteries...and it's constantly changing. 😂
@_veikkomies
@_veikkomies 2 жыл бұрын
A lot of IDEs and I think even VSCode changes the dot to an arrow automatically.
@chiefsittingstill6061
@chiefsittingstill6061 2 жыл бұрын
Eclipse IDE auto converts the dot to an arrow... reasonably reliably.
@Yakbox
@Yakbox 10 ай бұрын
U tried well but I'm not been able to catch up 😅
@vor946
@vor946 2 жыл бұрын
Literally today I had the biggest puzzle with dereferencing smart pointer of pointer to class made with make_unique. For some reason I had to use *(smart_ptr)->method(). For the same reason probably I couldn't just smart_ptr.get().method(). Can someone explain this? Is it because of the type of the smart pointer?
@privileged6453
@privileged6453 2 жыл бұрын
if you create the pointer via make_unique (eg: auto ptr = make_unique();) then you can call a method as if 'ptr' were a regular pointer (eg: ptr->method();)
@MrFedX
@MrFedX 2 жыл бұрын
If you had a pointer to pointer to a class, then I think it makes sense. You need to dereference the first pointer (*) so you get the second pointer. And then you dereference that pointer (->) and you have access to the actual class (method()).
@privileged6453
@privileged6453 2 жыл бұрын
@@MrFedX if your unique pointer is holding a pointer then yes, you’d need to do that. But I don’t really see where that would ever be the case
@vor946
@vor946 2 жыл бұрын
TinyXML lib was returning such pointers, that just could not be turned into smart pointers via the usual methods. What only was annoying is that I figured how to do it by hit or miss approach. Nice lesson though, haha.
@sumitbhosale3401
@sumitbhosale3401 2 жыл бұрын
Thanks. Can You Make Video On Efficient Permutation Of String. Any Best & Fast Algo For Permute String & Numbers.
@JacobSorber
@JacobSorber 2 жыл бұрын
Maybe. What are you trying to do with the string?
@Metadaxe
@Metadaxe 2 жыл бұрын
1:35 the decadence. the indulgence. slothful.
@DarkSun1988
@DarkSun1988 2 жыл бұрын
But when I need to use a pointer instead of a variable?
@JacobSorber
@JacobSorber 2 жыл бұрын
Ah, good question. I'll add that to my topic list, and see what I can do in a future video.
@islandcave8738
@islandcave8738 2 жыл бұрын
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).
@torarinvik4920
@torarinvik4920 2 жыл бұрын
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.
@Alche_mist
@Alche_mist 2 жыл бұрын
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++.
@torarinvik4920
@torarinvik4920 2 жыл бұрын
@@Alche_mist absolutely. Systems like Sega Genesis has a solid C compiler, but C++ is not possible/practical.
@Hauketal
@Hauketal 2 жыл бұрын
@@Alche_mist This is why a cross-compiler is used for constrained systems. Even on Arduino development happens in C++ by default.
@puncherinokripperino2500
@puncherinokripperino2500 2 жыл бұрын
Weird reasoning for -> operator, why don't just use . for pointers too?
@MrFedX
@MrFedX 2 жыл бұрын
You can. You just have to dereference the pointer first. :)
@puncherinokripperino2500
@puncherinokripperino2500 2 жыл бұрын
@@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.
@christianrazvan
@christianrazvan 6 ай бұрын
Why not double points .. ? The -> seems cumbersome as f...
@henami552
@henami552 2 жыл бұрын
What i dont quite understand is why the dot operator wasnt simply overloaded to work with pointers.
@JacobSorber
@JacobSorber 2 жыл бұрын
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.
@henami552
@henami552 2 жыл бұрын
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.
@rustycherkas8229
@rustycherkas8229 2 жыл бұрын
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...
@Simple_OG
@Simple_OG 4 ай бұрын
When you have a pointer to struct use -> otherwise use .
@smartphonesammler3924
@smartphonesammler3924 2 жыл бұрын
This is arguably the most unnecessary feature in c++.
@jp5000able
@jp5000able 2 жыл бұрын
No! I find it extremely useful. I can greatly simplify my code when I'm dealing with complex structures.
@ahmetkarakartal9563
@ahmetkarakartal9563 Жыл бұрын
thanks
@theprince3736
@theprince3736 2 жыл бұрын
thanks
@hapashreguiem7460
@hapashreguiem7460 2 жыл бұрын
Thanks
Are Vectors Slower than Arrays?
8:58
Jacob Sorber
Рет қаралды 30 М.
The What, How, and Why of Void Pointers in C and C++?
13:12
Jacob Sorber
Рет қаралды 53 М.
Electric Flying Bird with Hanging Wire Automatic for Ceiling Parrot
00:15
Новый уровень твоей сосиски
00:33
Кушать Хочу
Рет қаралды 3,9 МЛН
Magic or …? 😱 reveal video on profile 🫢
00:14
Andrey Grechka
Рет қаралды 82 МЛН
When do I use a union in C or C++, instead of a struct?
11:18
Jacob Sorber
Рет қаралды 69 М.
The Arrow Operator in C++
7:53
The Cherno
Рет қаралды 217 М.
Pulling Back the Curtain on the Heap
21:38
Jacob Sorber
Рет қаралды 37 М.
How Memory Usage Slows Down Your Programs
9:17
Jacob Sorber
Рет қаралды 19 М.
Learn Any Programming Language In 3 Hours!
22:37
Code With Huw
Рет қаралды 375 М.
How computer processors run conditions and loops
17:03
Core Dumped
Рет қаралды 88 М.
One reason to Modify your Memory Allocator (C/C++)
10:23
Jacob Sorber
Рет қаралды 33 М.
Making variables atomic in C
11:12
Jacob Sorber
Рет қаралды 37 М.
What's the Best Way to Copy a Struct in C and C++?
13:44
Jacob Sorber
Рет қаралды 34 М.
How principled coders outperform the competition
11:11
Coderized
Рет қаралды 1,7 МЛН
Electric Flying Bird with Hanging Wire Automatic for Ceiling Parrot
00:15