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.
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)
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.
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.
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.
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 :)
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.
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.
@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.
@@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.
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
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.
@@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.]
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 :)
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!
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.
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.
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'.
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.
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.
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) ?
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.
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
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.
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.
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.
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.
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
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
As a beginner I've been struggling with this concept for weeks now, but your video essentially clarified everything in my head. Thanks mate!!!
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.
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)
Thanks!!!
You are very good at explaining, clear with your choice of words and very calm. You could be a very good teacher.
This was so helpful. You explaind like it is so simple.I hope i don't get confused again.
but you will.. :)
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.
It’s so much easier to understand with your explanation & examples. Great thanks :)
Really done well, never had a single problem understanding this!
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.
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.
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 :)
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.
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.
Black DiamondPL thank you! really really help.
@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.
@mytech6779 thank you, that was awesome
thank you very much. remarkably clear. its like you made zero mistakes. remarkable actually
Very nice, clean and comprehensive tutorial. Thanks!
Thanks!
Giving examples is 50% of making sure someone understands it. The other 50% is testing stuff out yourself.
my mind has exploded.
Nice Try M9: 🤯
Is your mind gravy?
best channel ever
Still helping people in 2021 btw...
i feel like this video didn't really explain the difference between ref and ptr.
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 ?
Same. He failed to explain the why or use cases. Practically a useless video.
why use printf over cout?
@@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.
all the man are kidding? almost features of c can use in c++... i like printf
@@arthur_camara how annoying. Not everyone knows C to assume this awfulness.👎🏿
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
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.
Use cout in C++ tutorials.
I actually preffer the printf syntax in many cases. It's like a more capable python print()
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 "
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
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.
@@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.]
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 :)
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!
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.
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.
+Paul Programming
Which IDE are you using?
It looks like Sublime Text to me
i second that
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'.
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.
very well explained thank you
what ide does he use?
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.
Great video!! Keep up the good work!
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) ?
to demonstrate how pointers work without causing any further confusion
Awesome content, thank you
can you explain about different way of return, like return by value, ...
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.
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.
10:05.
Hah, totally my bad.
Thanks for the feedback. I have a video in the works that I am expecting to publish next weekend that will discuss & and * more.
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
Sounds great. Looking forward to it!
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.
Great video, thanks!
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.
Mr. Programming what font are you using in that term and is that an xterm the font is nice.
Why not use an IDE?
My man.
GREAT EXPLAINED :)
i simply love you
Finally i got it!!!!
you should print it step by step not all in one go, as a novice my mind is freaking out ahaha
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.
which IDE are you using?
Sublime Text
Thanks a lot!
it’s 2016. why would you use C based libs and C based prinf?
c++ is superset of c that means any c code can be build and run with c++ compiler
@@SerhatAtes There is one keyword in C that has no equivalent in C++. I don't know why, maybe just to make people ask.
Which editor do you use?
OK, I found here(comments). sublime-text
10/10
great!
Eccezionale!
Anyone else learning c++ as a beginner
it would be great to talk with another person...
Yeah, here, +254758403330
@@sammiekarani371 from which country u r ?
is this ur whatsapp number
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.
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.
In conclusion reference and pointer works the same. So use reference all the time because pointer is kind of confusing...
Sorry, but wh you are using printf and not cout?? printf is more in C. Cout you are using in C++
printf() is superior in several ways, cout is not great.
i guess there are centrists in the dark/light mode community too
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
Clearly it's c, c++ use cout and not printf
Clearly it's not c, since it's illegal to pass by reference in c!
Its C++ but hes using syntax from C which from what I've been told while yes it works is bad practice
c++ is superset of c that means any c code can be build and run with c++ compiler
I think it is a c, but not c++
No.
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++.
c++ is superset of c that means any c code can be build and run with c++ compiler
They should fire college professors and use this video instead.
Yeah, I think I'm just going to stick to passing by references! I'm gonna stay away from pointers!!
Thank you!!!