What is the Difference Between Pass By Value, Pass By Reference, and Pass By Pointer, C++

Поделиться
HTML-код
  • Опубликовано: 27 ноя 2024

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

  • @rajatmig29
    @rajatmig29 5 лет назад +18

    paul, the way you explain and the calmness in your voice combine to give the viewer a very good experience. keep up the good job

  • @andrewr.3478
    @andrewr.3478 6 лет назад +21

    As a beginner I've been struggling with this concept for weeks now, but your video essentially​ clarified everything in my head. Thanks mate!!!

  • @sandlertossone1813
    @sandlertossone1813 Год назад +3

    Should make a series on C++. I've looked at a ton of video's on this and understand pointers. Your video's on these are the best of them all. After years of being confused or not being clear on certain small details on these subjects, you really cleared them up for me so a huge thank you. I hope you make a series on C++ explaining classes, inheritance, arrays, and other basics.

  • @mytech6779
    @mytech6779 3 года назад +22

    Just for those passing by, the C++ committee recommendation is that raw pointers should no longer have a place in user code (as opposed to a few specific uses inside the STD library)
    std::unique_ptr is a full replacement for raw pointers with identical runtime performance while eliminating potential memory leaks.(unique_ptr also replaces auto_ptr)

  • @Sof_net
    @Sof_net 5 лет назад +1

    You are very good at explaining, clear with your choice of words and very calm. You could be a very good teacher.

  • @ezgieftekin4495
    @ezgieftekin4495 7 лет назад +5

    This was so helpful. You explaind like it is so simple.I hope i don't get confused again.

  • @Shazbazz
    @Shazbazz 3 года назад +6

    I feel like I understand pointers better now, but I still don't understand why you would ever want to use them if you just just pass by reference instead.

  • @vantran1189
    @vantran1189 4 года назад +1

    It’s so much easier to understand with your explanation & examples. Great thanks :)

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

    Really done well, never had a single problem understanding this!

  • @WonderCloudHD
    @WonderCloudHD 7 лет назад +3

    I just wanted to say thank you for this great video. The examples you have provided were very helpful and very beneficial to my learning. I was really able to see the differences between the three methods, and really understand the concepts. Thank you.

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

    If you pass in the ref you are using the actual value. If you pass in the value you are passing in a copy. Thank you for telling me a straight answer !
    besides the value been the copy and the ref the real thing being a stupid way of doing it, people in the community make it far worse by being cryptic about it.

  • @Nippius
    @Nippius 8 лет назад +14

    Maybe I've missed something but i'm confused. What's the difference between using a reference and a pointer? They are both manipulating the same variable but when using a pointer you need the extra step of dereference it? Apart from that it's a good tutorial especially for people like who need to see things actually working :)

    • @PaulProgramming
      @PaulProgramming  8 лет назад +14

      The easiest way to think about it is that a pointer can usually be instructed to point to different things over time, whereas a reference is referring to a specific thing.

    • @siniarskimar
      @siniarskimar 6 лет назад +20

      To answer your question you need to know how computer gets data dynamically / from RAM.
      When creating a variable, VALUE is strored inside RAM with given cell address (RAM has cells, in which values are stored). NAME of variable is stored in different computer chip, let's call it "index chip" for now.
      This chip is like a map for a computer.
      When you use a normal variable, computer goes to this 'index chip' and gets it's name along with address in order to get the value.
      name ('index chip') ->address -> value
      This system is working fine, but can be slow as your program grows. This where pointers come in.
      Pointers store the addresses, as mentioned ealier, so computer doesn't need to search 'index chip'.
      Computer already knows the address, because of pointer, so it has direct way to get value.
      On top of that pointer can point/store any address. Meaning you can change where poiner is pointing at any time.
      They are also the way to make dynamic allocation work
      Ok, so pointer give us speed. What are references?
      References are like additional names to our address. THEY ARE NOT storing addresses! So when creating a reference, you are telling computer exactly what VARIABLE you want to have. In result, somewhat ignoring variable scope. Another difference is that, references are just names, so computer needs to do the same process of getting value as normal variable does.
      Summarizing:
      -Pointers are created for speed.
      -References are created for easier access.

    • @suhaimiannuar6008
      @suhaimiannuar6008 6 лет назад

      Black DiamondPL thank you! really really help.

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

      ​@Name I thought i would have a short addition to the other comments but got carried away, anyway seams like a shame to delete it now.
      There are several layers of abstraction when including the operating system, but there generally is no "index chip". The operating system and CPU can see "real" memory addresses. "Real" as given by the memory controller, which is usually a chip on the motherboard that combines multiple physical modules and chips and converts basic linear address numbers used by the CPU to and from whatever is needed inside the actual memory chips. This is so the programmer does not need detailed information on exact hardware and so that the CPU does not need to be designed for exact memory hardware.
      The operating system will load an application into a chunk of memory and translates the real addresses of that chunk into virtual addresses. Another way to imagine it is that the compiled program uses relative addresses and the OS assigns the starting address. This way the compiled application is not hard coded to need a fixed set of real memory addresses.
      The CPU then starts reading binary instructions from the first memory address where the program was loaded. These instructions will include other memory addresses for the CPU to read either data or for a jump to another instruction(if not executing in order). So at the base level of the program it is all essentially pointers. THERE ARE NO OBJECT NAMES AT THE MACHINE LEVEL! (meant to be bold not yelling) At the machine code level there are only starting addresses and byte counts to fetch from those address and instructions for what to do to those fetched bytes. All the programming high level conceptual junk is wiped away.
      Now to understand the high level programming ideas of pass by value, ref, and pointer you need to understand the global-stack-heap allocation of memory that most programs use. The global part is where the base program was and is loaded into RAM, then small temporary chunks of RAM [frames] are stacked on this for each function call, this is the "stack". Pass by value is a copy operation and the required data from the global space is copied to the stack frame for use by the function, again kind of like the situation with the main application and OS the function typically only knows relative addresses within its frame. The function at compile time would not normally know addresses in the global area nor the relative distance to global. When the function operation is complete its frame is destroyed "popped of the stack". When a function calls a function you get more frames stacked up and this is why a function can't know its relative position to global variables at compile time because it won't know its stack height or or the global area size.
      Some high level programming languages copy values by default and others pass by reference by default, it is only a design choice to fit a programming style. No hardware or strict logic constraints require one or the other to be the default.
      "Reference" will use the existing address of an object [data] rather than creating a copy at a new address that is within the current stack frame. At a final machine code level there is no difference between a ref and a pointer but there is some difference at the compiler [optimizer] level and for ease of programming. The referenced object address can be in global, stack, or heap. So both value and ref are created as pointers within the binary machine code, but they are specific restricted use cases so the compiler can better optimize and the programmer gets less bugs debug.
      A "pointer" can be assigned any address and can be used with math [just like an int math] to alter the pointed at address while the program is running.
      The array syntax "z[0]" is syntax sugar, it is really just pointer math. "= z[3]" is the same as "= *ptr + 3" the pointer form gets complex with multi-dimensional arrays.
      Pointers are commonly used with heap memory, although they can be used with stack and global there is not much need.
      Heap is not orderly like the stack of frames, but heap is able to store much larger data structures and keep them for arbitrary lengths of time as heap memory is only released manually; either explicitly within the program(best), by a garbage collector function (easy but not suitable for some programs due to unpredictable lag, and may not catch 100% of leaks), or heap is always released when the program terminates and all of its memory is recovered by the OS (bad choice, only suitable for the most simple and well considered programs, otherwise this is an almost certain memory leak).
      Objects stored on the heap are sort of a cross between stack and global, like stack they are not part of the base machine code and so are safer to manipulate without changing important starting values, and like global objects heap objects are not tied to the life of a function call or the fixed size of a stack frame.
      So the real underlying question is why waste time copying a value?(I mean where you are not required by logic to save the original value) Its a safer style and easier to debug, and the way it copies is basically at no performance cost, the variable is read from the original address into the CPU register, used for whatever the function needs, then the result is written to the new address instead of overwriting the original address. In other words when properly compiled and optimized there is no separate copy step it is just dumping the output in location B instead of A.

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

      ​@mytech6779 thank you, that was awesome

  • @pepe6666
    @pepe6666 5 лет назад +1

    thank you very much. remarkably clear. its like you made zero mistakes. remarkable actually

  • @hannahm9259
    @hannahm9259 4 года назад +1

    Very nice, clean and comprehensive tutorial. Thanks!

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

    Giving examples is 50% of making sure someone understands it. The other 50% is testing stuff out yourself.

  • @solaaar3
    @solaaar3 7 лет назад +56

    my mind has exploded.

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

    best channel ever

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

    Still helping people in 2021 btw...

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

    i feel like this video didn't really explain the difference between ref and ptr.

  • @amolgaikwad4114
    @amolgaikwad4114 4 года назад +2

    I would like to to know, pass_by_reference and pass_by_pointer gives same result, so when to use pass_by_reference and when to use pass_by_pointer ?

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

      Same. He failed to explain the why or use cases. Practically a useless video.

  • @tajrianislam4993
    @tajrianislam4993 6 лет назад +8

    why use printf over cout?

    • @vertigo6982
      @vertigo6982 5 лет назад +6

      @@arthur_camara he should change the title to C mixed in with C++. It's misleading to teach C and say it's C++. It's bad practice imo. ESPECIALLY in a Pointers video! Might as well call this video C with Pointers.

    • @winhtut1187
      @winhtut1187 5 лет назад +2

      all the man are kidding? almost features of c can use in c++... i like printf

    • @cabreram.4734
      @cabreram.4734 5 лет назад +1

      @@arthur_camara how annoying. Not everyone knows C to assume this awfulness.👎🏿

  • @industrialdonut7681
    @industrialdonut7681 4 года назад +1

    I'm a little confused only on why doing *ptr = 30; works like it does. I would've thought that doing *ptr anywhere is an 'r value' and thus can't assign something to it

    • @chuckwieser7622
      @chuckwieser7622 4 года назад

      I am confused too Paul Programming... Why does "ptr" = "xptr", making them both 30?
      thank you for your video in any help clearing up this question we.

  • @Metastate12
    @Metastate12 5 лет назад +27

    Use cout in C++ tutorials.

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

      I actually preffer the printf syntax in many cases. It's like a more capable python print()

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

      Tbh sometimes using printf is better, at least for me, for example if I'm gonna be needing a lot of place holders I don't wanna spam "

  • @SerhatAtes
    @SerhatAtes 4 года назад

    i saw in comments that people confused about c syntax; c++ is superset of c that means any c code can be build and run with c++ compiler

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

      You're certainly right with that fact. However the people are right about the use of the syntax, it's clearly c++ so you should use the idiomatic syntax of c++, which involves the use of std::cout in the standard library and avoid using the C libraries and functions.

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

      @@checho_tala Mostly, but I believe printf() syntax is superior to cout for many uses, printf() is even superior to python print().
      [ And have you ever tested the effect on compile optimization, huge improvement with printf() vs cout, though this is not a concern unless there is a lot to print. Also "
      "; is usually better than ::endl; though endl will always flush the buffer
      may not be flushed immediately.]

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

    Thank You, Cool video, but most important element is not explained. Why reference is added to c++ if pointer is able to do the same thing. So, reference is redundant so far, but it has to be a reason it was added to c++, and if You have a title "What is the difference..." I would expect that the reason is more important than execution mechanics :) ...if anybody knows a video where the reason is explained, I will be supper grateful :)

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

    Sorry for asking this rookie question, but I thought that in C++ you would normally use: cin/cout , instead of printf/scanf and all the placeholders. Can I use both? Video is amazing btw!

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

      You might of figured it out but printf and scanf I believe are from C. Since C++ is a superset of C it makes most C code valid in C++. So cin and cout is the C++ way to input and output information and printf and scanf is the C way to input and output information.

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

    him: ***writes in cpp***
    also him: Imma use the motherf*ing format specifiers here too....
    I know the above joke is silly, but I had to do it.
    Anyway, great content. Keep'em coming.

  • @varun_n1729
    @varun_n1729 7 лет назад +2

    +Paul Programming
    Which IDE are you using?

    • @bla7091
      @bla7091 7 лет назад

      It looks like Sublime Text to me

    • @Farligefinn
      @Farligefinn 7 лет назад

      i second that

  • @SpellsOfTruth
    @SpellsOfTruth 5 лет назад

    Is this correct?
    -use pointers and pointer refs when datatype is larger than primitive datatype
    -diff between pointer and reference is that a pointer can point to more than 1 addr while a ref points only to 1 addr.
    -diff between func(I64 ptr), func(I64 &ptr), func(I64 *ptr), func(I64 * &ptr):
    -pass by value means copy param and param will not change at the end of function
    -pass by ref means no copy param and param will change at the end of function
    -pass by pointer means copy param and param will not change at the end of function
    -pass by pointer ref means no copy and param will change at the end of function
    -line carot '->' does not mean 'points to', it simply means ptr 'accesors' just like the dot '.' key means 'accessor'.

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

    So a reference functions as if it's a sort of "static" pointer, referring only to the named variable and cannot be changed to point to a different one.

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

    very well explained thank you

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

    what ide does he use?

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

      Looks like GNU-linux just a text editor and the Bash command line. Though he could have combined 'clear ; compile && execute' into one line that can be recalled with the up arrow. I Even mapped the equivalent of save and all that that to the F5 key in my text editor, "F5" BAM! save compile execute.

  • @zieglerai
    @zieglerai 7 лет назад +1

    Great video!! Keep up the good work!

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

    Thanks for the video, by the way, helped me understand this stuff. Question...
    In the video: int* xptr = &myVal; //...why not just use passByPtr(&myVal) ?

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

      to demonstrate how pointers work without causing any further confusion

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

    Awesome content, thank you

  • @ThanhTrantrancongthanh
    @ThanhTrantrancongthanh 8 лет назад +1

    can you explain about different way of return, like return by value, ...

    • @michrisoft
      @michrisoft 7 лет назад +1

      return by value would just be making the function an int/double/float/etc. instead of a void and having a return val; at the end.

  • @TheAwesomeDudeGuy
    @TheAwesomeDudeGuy 8 лет назад +13

    I found it weird that you could make a 14 minute video on this subject without mentioning the word "address".
    Also, it wasn't clear what exactly each operator (& and *) does.

    • @GenerationzYT
      @GenerationzYT 8 лет назад +5

      10:05.

    • @TheAwesomeDudeGuy
      @TheAwesomeDudeGuy 8 лет назад

      Hah, totally my bad.

    • @PaulProgramming
      @PaulProgramming  8 лет назад +1

      Thanks for the feedback. I have a video in the works that I am expecting to publish next weekend that will discuss & and * more.

    • @GenerationzYT
      @GenerationzYT 8 лет назад

      Paul Programming It's actually really convenient you posted this video, as I just had a fellow class mate ask me about all three of those examples. So I linked him the video yesterday. Thanks for making my job easier xP

    • @TheAwesomeDudeGuy
      @TheAwesomeDudeGuy 8 лет назад

      Sounds great. Looking forward to it!

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

    i didnt really understand the difference betwen pass by reference and pointer, one takes the real variable, and the other takes the value of the variable. but... in which scenarios one is better than the other.. i think i would need some more examples to really understand the difference. Thank you anyways.

  • @tylermccloudd6020
    @tylermccloudd6020 4 года назад

    Great video, thanks!

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

    It would be perfect to add "ptr += 10" or something to manipulate inside passByPtr function, and print 'ptr' itself before & after in main.
    Spoiler alert: It would not change.

  • @OssaGhalyoun
    @OssaGhalyoun 8 лет назад

    Mr. Programming what font are you using in that term and is that an xterm the font is nice.

  • @nielsdaemen
    @nielsdaemen 5 лет назад +1

    Why not use an IDE?

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

    My man.

  • @mateuszsmendowski2677
    @mateuszsmendowski2677 5 лет назад

    GREAT EXPLAINED :)

  • @DJHyunKim
    @DJHyunKim 4 года назад

    i simply love you

  • @mrpor9541
    @mrpor9541 6 лет назад

    Finally i got it!!!!

  • @Emester123
    @Emester123 6 лет назад +1

    you should print it step by step not all in one go, as a novice my mind is freaking out ahaha

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

    You explain what it does, but you did not give any use cases for passing by copy or pointer. So I still don't understand why we really would do each of these.

  • @solaaar3
    @solaaar3 7 лет назад

    which IDE are you using?

  • @nailsonlandimprogramming
    @nailsonlandimprogramming 5 лет назад

    Thanks a lot!

  • @postmaster2211
    @postmaster2211 5 лет назад

    it’s 2016. why would you use C based libs and C based prinf?

    • @SerhatAtes
      @SerhatAtes 4 года назад

      c++ is superset of c that means any c code can be build and run with c++ compiler

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

      @@SerhatAtes There is one keyword in C that has no equivalent in C++. I don't know why, maybe just to make people ask.

  • @eldarismailov655
    @eldarismailov655 7 лет назад

    Which editor do you use?

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

    10/10

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

    great!

  • @mattiacervo8258
    @mattiacervo8258 7 лет назад

    Eccezionale!

  • @umarajmal6216
    @umarajmal6216 4 года назад

    Anyone else learning c++ as a beginner
    it would be great to talk with another person...

  • @swarnasekhardas8576
    @swarnasekhardas8576 6 лет назад

    The code which you wrote of pass by reference is not working.There is error is this:
    void passByRef(int & ref);
    Later i found the error. Actually c does not support pass by reference, c++ supports. If you write this in c++ it will work fine.

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

      For the writing portion C is a part of C++. I Think you mean if you use a C++ compiler it will work but not with a C compiler.

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

    In conclusion reference and pointer works the same. So use reference all the time because pointer is kind of confusing...

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

    Sorry, but wh you are using printf and not cout?? printf is more in C. Cout you are using in C++

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

      printf() is superior in several ways, cout is not great.

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

    i guess there are centrists in the dark/light mode community too

  • @bombdotcomist
    @bombdotcomist 4 года назад

    I'm sorry but 12:36 line 13 makes no sense. The output should print out the ADDRESS of the xptr, NOT the value. Suggest you make a proper video that better explains this

  • @ktan18879
    @ktan18879 7 лет назад

    Clearly it's c, c++ use cout and not printf

    • @Farligefinn
      @Farligefinn 7 лет назад +4

      Clearly it's not c, since it's illegal to pass by reference in c!

    • @ShadowBurn680
      @ShadowBurn680 6 лет назад

      Its C++ but hes using syntax from C which from what I've been told while yes it works is bad practice

    • @SerhatAtes
      @SerhatAtes 4 года назад +1

      c++ is superset of c that means any c code can be build and run with c++ compiler

  • @supertonyxd
    @supertonyxd 6 лет назад

    I think it is a c, but not c++

    • @user-vn4yl3fr9f
      @user-vn4yl3fr9f 5 лет назад

      No.

    • @kopuz.co.uk.
      @kopuz.co.uk. 5 лет назад

      Yeah you're right.. so many people must think that they're writing correct c++ but in reality its mostly c with a hint of c++.

    • @SerhatAtes
      @SerhatAtes 4 года назад +1

      c++ is superset of c that means any c code can be build and run with c++ compiler

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

    They should fire college professors and use this video instead.

  • @Reivivus
    @Reivivus 7 лет назад

    Yeah, I think I'm just going to stick to passing by references! I'm gonna stay away from pointers!!

  • @divyasoneji2639
    @divyasoneji2639 4 года назад

    Thank you!!!