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

Комментарии • 100

  • @georgecop9538
    @georgecop9538 3 года назад +81

    So, basicly the arrow operator is an alternative for (*structname).property, but it's easier to use structname->property

    • @whymyruffles
      @whymyruffles 2 года назад +2

      Exactly, it's much simpler and clear that way

    • @jeanmahe8657
      @jeanmahe8657 Год назад +1

      Thank you this isnt explained anywhere

  • @ZachBradyisBrachZady
    @ZachBradyisBrachZady 3 года назад +9

    Fantastic. this video is precisely what I have been looking for three weeks ago

  • @whamer100
    @whamer100 3 года назад +7

    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 Год назад +1

    one of the simplest yet best explanation!!

  • @mohamadbitar1788
    @mohamadbitar1788 Месяц назад

    thank you so much this was such a nice and a simple explanation!

  • @Recovered
    @Recovered 3 года назад +1

    In 5 minutes you clarified something that has mystified me for years. Nobody ever explained it as well as you just did!

  • @imtiazsabree6562
    @imtiazsabree6562 Год назад

    Thanks. Easy and straightforward.

  • @leythecg
    @leythecg Год назад +1

    Excellent tutorial! Very understandable and straight to the point! Many thanks for this!

  • @sheikhmuhammedtadeeb5677
    @sheikhmuhammedtadeeb5677 2 года назад +18

    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.

  • @GAMarine137
    @GAMarine137 4 месяца назад

    Nice refresher

  • @hafizsakib2734
    @hafizsakib2734 Год назад

    Crystal Clear Sir!

  • @Mom_X_Son
    @Mom_X_Son 2 месяца назад

    Lovely and simple

  • @ronnysherer
    @ronnysherer 3 года назад

    Great short and pinpointing explanation.

  • @ko6ghy
    @ko6ghy 3 года назад +2

    Worth mentioning that if you pptr++ the pointer will be advanced by the size of the structure it points to.

    • @prasantkumarmahato8034
      @prasantkumarmahato8034 3 года назад

      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 3 года назад +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 3 года назад

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

  • @cprogramming5640
    @cprogramming5640 3 года назад +1

    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.

  • @CaptainClaw123
    @CaptainClaw123 2 года назад

    It was helpful thank you :)

  • @zulfazlihamjah8897
    @zulfazlihamjah8897 Год назад

    wow, this channel is very developer friendly. The theme all dark by default🤣

  • @glee21012
    @glee21012 3 года назад +3

    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 3 года назад

      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 3 года назад

      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 3 года назад +1

      @@gregoryfenn1462 that's just c#.

    • @glee21012
      @glee21012 3 года назад

      @@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 3 года назад

      @Yusuf Kazi struct and class are the same things in C++, and they are automatically types (no typedef bs required)

  • @Yakbox
    @Yakbox Год назад +1

    U tried well but I'm not been able to catch up 😅

  • @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?

  • @Vulto166
    @Vulto166 2 года назад

    This one goes to my "watch later" list.

  • @benjaminshinar9509
    @benjaminshinar9509 3 года назад +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 3 года назад

      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 (*)[ ]".

  • @simonlaflamme8840
    @simonlaflamme8840 5 месяцев назад

    What about arrays and an array of pointers?

  • @md.mohiulislam6516
    @md.mohiulislam6516 2 года назад

    tnx brother. but what about ">>"?

  • @michaelacodes
    @michaelacodes 2 года назад

    thank you

  • @elalemanpaisa
    @elalemanpaisa 3 месяца назад

    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.

  • @Earth-Worm-Tim
    @Earth-Worm-Tim 2 года назад +1

    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!!!

  • @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

  • @siddharthasarmah9266
    @siddharthasarmah9266 3 года назад

    great video!! thanks

  • @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?

  • @johnsknows3135
    @johnsknows3135 2 года назад

    cheers
    !!!

  • @electromatic2014
    @electromatic2014 3 года назад

    First comment!, fellow C programmer, keep It up, nice video !!

  • @hapashreguiem7460
    @hapashreguiem7460 3 года назад

    Thanks

  • @TheVertical92
    @TheVertical92 3 года назад +12

    would be great if you make a video on the other arrows 😁
    It really confused me using 'cout

    • @ronnysherer
      @ronnysherer 3 года назад +3

      The

    • @TheVertical92
      @TheVertical92 3 года назад +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  3 года назад +2

      Thanks for the suggestion. I'll add it to the list.

  • @andydelle4509
    @andydelle4509 3 года назад +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.

  • @rogo7330
    @rogo7330 3 года назад +5

    I think your pretty → symbol can confuse somebody in this kind of tutorial :D
    It's just a '->' arrow, guys. Your CO

    • @avonray9147
      @avonray9147 3 года назад

      How do I get the arrow as a single character? And will it work with any compiler?

    • @robbieman6265
      @robbieman6265 3 года назад

      @@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  3 года назад +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. (ruclips.net/video/5td9upDbkaU/видео.html)

  • @judedavis92
    @judedavis92 3 года назад

    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 3 года назад +4

      No overhead compared to the ""ugly" way. Just "syntactical sugar" - the generated assembly is the same.

  • @Metadaxe
    @Metadaxe 3 года назад +1

    1:35 the decadence. the indulgence. slothful.

  • @DarkSun1988
    @DarkSun1988 3 года назад

    But when I need to use a pointer instead of a variable?

    • @JacobSorber
      @JacobSorber  3 года назад

      Ah, good question. I'll add that to my topic list, and see what I can do in a future video.

    • @islandcave8738
      @islandcave8738 3 года назад +1

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

  • @yousefsadeek6640
    @yousefsadeek6640 2 года назад

    damn explain man! 🤍

  • @_veikkomies
    @_veikkomies 3 года назад +1

    A lot of IDEs and I think even VSCode changes the dot to an arrow automatically.

    • @chiefsittingstill6061
      @chiefsittingstill6061 3 года назад

      Eclipse IDE auto converts the dot to an arrow... reasonably reliably.

  • @giovannibianchessi1578
    @giovannibianchessi1578 3 года назад +1

    Great video thank you!
    But, in this video one thing isn't clear to me... How old are you, Jacob? 😁

    • @JacobSorber
      @JacobSorber  3 года назад +2

      It's one of life's great mysteries...and it's constantly changing. 😂

  • @limit1586
    @limit1586 8 месяцев назад

    let me give you an advice. Type at the top of your programs using namespace std; . You can type things without that std::

  • @sumitbhosale3401
    @sumitbhosale3401 3 года назад

    Thanks. Can You Make Video On Efficient Permutation Of String. Any Best & Fast Algo For Permute String & Numbers.

    • @JacobSorber
      @JacobSorber  3 года назад

      Maybe. What are you trying to do with the string?

  • @torarinvik4920
    @torarinvik4920 3 года назад

    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 3 года назад

      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 3 года назад

      @@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 3 года назад

    Weird reasoning for -> operator, why don't just use . for pointers too?

    • @MrFedX
      @MrFedX 3 года назад

      You can. You just have to dereference the pointer first. :)

    • @puncherinokripperino2500
      @puncherinokripperino2500 3 года назад

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

  • @henami552
    @henami552 3 года назад

    What i dont quite understand is why the dot operator wasnt simply overloaded to work with pointers.

    • @JacobSorber
      @JacobSorber  3 года назад

      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 3 года назад

      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 8 месяцев назад

    When you have a pointer to struct use -> otherwise use .

  • @christianrazvan
    @christianrazvan 10 месяцев назад

    Why not double points .. ? The -> seems cumbersome as f...

  • @smartphonesammler3924
    @smartphonesammler3924 2 года назад +1

    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.

  • @theprince3736
    @theprince3736 2 года назад

    thanks

  • @christopherbarrett9900
    @christopherbarrett9900 2 года назад

    Thanks

  • @ahmetkarakartal9563
    @ahmetkarakartal9563 2 года назад

    thanks