#BB12 Pointer vs References - and why you don't need 👉pointers in C++

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and welcome to my short Series where we explore certain features of the C++ language in an Arduino environment hints tips tricks and traps now before we start talking about pointers smart pointers references or anything like that let's think about why there's even a perceived need for this yeah after all if you're looking at the code on the screen we've been calling functions without such um additions to our code for decades right we just write a function give it some parameters call it it and uh everything's great we don't need anything else or do we I want to have a big shout out for PCB way PCB prototype the easy way now you know I've had many many pcbs created by PCB way and now they've got a up to 50% off PCB way Christmas sale let's have a look so this is running from the 1st of December to the 31st of December and it's up to 50% off as you can see there's lots and lots of coupons available so that's a good chance to get that PCB ordered and you you can get started with just $5 and remember your first PCB is absolutely free look at the front page again if you're new this is free for your first order look at that it's certainly worth trying them out and if you're an experienced PCB designer you can get things like aluminium pcbs as it shows you here not just that of course they do many many different types of PCB flexible ones custom bespoke assembly you name it they do it and not just that they even do CNC 3D printing the options here are endless certainly worth a look and I highly recommend them PCB way PCB prototype the easy way let's look at the code on screen then now you can see there first of all there's a very simple swap function that I've written yeah now before we start looking at the code yes this is written in platform iio or or at least it's it's running on Visual Studio code I've got platform IO um installed but I'm not actually using platformio as such for this demo and you can replicate this on your Arduino or within Visual Studio code yourself quite happily but I'm not going to go anywhere near that it just takes far too long so let's have a look at this swap function all it's going to do is literally take two digits uh in this case double a double b and go swap them over yeah that sort of function is used all the time in sorts and things uh so a becomes b b becomes a simple right so well what is there to it yeah we're going to have a temporary variable that takes the value of able a uh able a then becomes equal to doubleb and double v becomes equal to the temporary variable da it's done takes all of a nanc and that's it and in here I've got this this long line here they just output something to the console so we can see what's going on and prove that it's working that a is now equal to b or what B was anyway and B is now equal to what a was and if you're thinking what an earth there's all this STD colon colon that's C++ and it's what you and me would be using if it were not for the Arduino framework that sort of hides all that from us you'd probably use something like what's on the next line some sort of Serial print or print line the trouble is to do that line above it with serial. print lines would take about four lines because you can't sort of put variables inside it can you so you'd end up doing with a Serial print inside swap function AA equals and then you have another one saying serial print AA and then another line saying serial print BB equals in quotes and then the final line serial print line saying uh this is the value of Double B it's all a bit convoluted and frankly I don't like it at all which is why I did an entire video on how we can get print F working inside an Arduino environment and yes yes it takes a little bit of memory but I mean unless your sketches are huge it's certainly worth the trouble of doing it because then you can write something like this which is concise and easy to understand you're saying inside swap function a a equals percent D which stands for a decimal value double b equals percent D another decimal value and then you give the decimal values that expect appear in order and whilst print f is not C++ it is actually C and C out the I'm using is C++ printf works great and I highly recommend it hence that video anyway moving on let's focus now on why we're using uh variables and references and so on just bringing things to a screeching halt for a second if you know all about functions you know what parameters are to a function and why we need them and what they can and can't do then use the chapter indications along the footer of this screen and skip to the bit where we talk about references and pointers don't hang around here getting bored uh being taught stuff you already know just saying Okay so we've written this this um function here then it just takes two integers now when you declare a function like this what you're actually tell you the compiler is I'm actually wanting an INT AA in the same way as we're saying int temp here except we've declared these up here as parameters to say declare these inges but these are actually incoming ones so allow these to be passed to me so if you know anything about what's going on behind the scenes the compiler says great I'll have a memory location for able A and A Memory location for double b and that's it that's that's where they're going to sit in your SRAM yeah when this function gets invoked now when this function as a whole finishes down here so all this is run and it gets to the bottom here it's printed something out at this point here these two variables dis disappearance The Ether they are no longer valid yeah because the the lifetime or the scope of those variables only exists for the life time of the function call right and you know all that I'm sure so let's have a look at the main function that calls this then to swap those two variables around okay here we have an INT main main is is the standard C or C++ entry point to any program bit like your Loop except this doesn't Loop Round unless you make it do so it just runs once and then stops and behind the scenes in Arduino World um there is a main so that you don't get to see it not usually anyway and the main says go and run the setup and then go and run the loop forever there's no magic to it that's what's happening but you never get to see that because the Arduino guys clever guys that they were hid all that from us and uh let us get on with the main job of setup and loop but here we have an actual main um and yes it does it's supposed to return an in when it stops anyway this function then has two integers A and B and we're outputting a line just like we did before to say right before we call anything let's just prove that A and B really equal what we think they do up here then we're going to call the swap function that we just had a look at and pass them those two variables A and B so what we're expecting at this point is a to become B and B to become a so we're saying a I want to be equal to 10 and b equal to five just swap them over right good and after the swap we're going to print out another line just to prove that it's done that and then the function ends and we always got to return something otherwise the compiler gets a bit knocky with us and and that's it really so let's just run this in its entirety uh and just see what the output looks like right there we are so it's just whiz through so it's saying before the swap a is equal to 5 as it would expect because that's what we said it to over here B is equal to 10 great that's that's bit there yes that's that Top Line there outputting that variable that message now inside the swap function it's go yes my incoming variables the two up here A A is equal to 10 and BB is equal to 5 I mean there's nothing magical about this there's no smoking mirrors it's as you'd expect it to happen and then after the swap when it's come back from the swap it says a a a is equal to oh hang on a minute a is equal to five again and B is equal to 10 hang on I thought we swapped these over all right I know lots of you are streets ahead of what I'm trying to say here and I guess I'm not really aiming this video at you am I I'm aiming this video to the people who don't quite understand what's gone on here how come it seems to have worked the swap bit inside the swap function but when it comes back from the swap function it's back to what it was before how can this be well the very uh very simple explanation is that when you pass parameters into a function like this this or perhaps more specifically when you pass them in where they've been declared like this what you're actually doing is just saying these integers that I'm declaring up here as the function as I said they're two independent memory locations they are not the same memory locations as these two here that we're passing in so you've got a as a memory location b as a memory location then you got double A and doubleb yeah and they're four independent memory locations so yeah the swap gets past values copied into its own variables so it gets a five and it gets a 10 it does its thing with it and that's it those those values it's mucked about with don't go anywhere they just disappear into the ether and then this function carries on and it goes well I've still got my A and B look then why would they be touched they're independent from anything else so hm now it could be useful then couldn't it for those variables to actually be updated and be seen to be updated from the calling program okay all that has come to the point where we now say yes now we need to understand how we can pass those variables into the swap routine the function here and have it actually update the original values here without creating copies in memory and all this all the other things yeah okay simple little change and and well almost the end of the video really so what I'm saying is then if we want to pass in the variables here so that what it's updating is not an independent copy of that variable but the actual variable that's been passed into it so it can change it and the calling routine can see that change we simply add in an Amper sand on there and on the other one and well before I explain what's going on just that one change let's run this again and see what kind of output we get down here and here we have it so we started off with a = 5 b = 10 within the swap function it was 10 and five when it comes back tra it's 10 and five again it's magic well no it's not magic actually it's references because what we've done here instead of declaring a simple integer int a a we're saying inte reference that I'm going to call a a as an alias but it's actually the real value that we're passing in what was that Ralph what are you talking about what let's put this a different way right we've got a cleaner screen now so what we're saying is we're declaring two integers here and we're passing them into this swap routine now as a consumer of that swap function you don't really know whether you're passing them in by value or whether you're paring them in by reference because the swap function could be Buri deep in a library somewhere that you have no interest in really other than to consume it and you might not know that it's actually going to change the value because the only change we did was add in this Ampersand and turn this integer AA into integer reference AA so it says I'm referring to the variable that's being passed into me as a a that I'm calling able a because after all the person who wrote the swap routine doesn't know what you're going to call it so it just makes up a name we could call it Fred we could even have called it a the same name as what you're passing in because it's just a name that only exists for the lifetime of this little function here yeah and disappears again after that so we're saying this is an integer reference now that I'm calling able a and this is an integer reference of Double B and by by reference mean we're referring to whatever it is that was passed in so we're referring to tr this variable here A and B here so we're referring to those ones and therefore yes we can indeed update those values and that because it's the same memory location we haven't created copies of them it's the same memory location and the value will obviously be seen by The Calling program and that is how you pass references in to a function by changing the function itself and say you put this Ampersand in which is a reference great that's it well we could actually stop the video now because to be quite honest within C++ that's about as much as you need to know yeah especially at the level at which we're aiming this video sort of the the beginner to to intermediate coder yes CU if you are screaming on the screens and you've forgotten this and you haven't told me that well you already know that I'm aing this at the beginner who has no idea what a reference is but hopefully now they do and that's that's as much as you need because within C++ you have this reference within C the old boys used to write c yeah they can't do this no you have to use a pointer oh no don't tell me about pointers well I could tell you about pointers it's complicated and I guess the only thing I want to tell you about pointers is so that if you see it in a program and there are plenty of libraries out there that use pointers because they're written by people who ostensibly are writing in C++ but they're not they're writing in C most of the time because that's probably where they've come from um well bit like what I was saying earlier on wasn't it where print F I mean everybody uses print F but it's c not C++ so should be using something else yeah like see out for example well it doesn't matter except that pointers are well I suppose we could use the word dangerous but um well yes let's use the word dangerous because the trouble with pointers is that they are exactly as their name implies they point to a particular memory location and you point to the wrong memory location because your coding is not optimal you're just pointing somewhere possibly in the middle of the stack the Heap the program memory I mean it could be pointing anywhere the onus is on you to get it right that's the problem with pointers behind the scenes sh don't tell anyone this but behind the scenes references like I just written up there with that ERS hand have got pointers all working for them behind the scenes but C++ sort of abstracts that away doesn't it it says look you don't have to worry about all that we all deal with that you just tell me it's a reference and I'll I'll do the necessary that makes it very very easy isn't it for us program it's just about amband as part of the declar ation of a function to say yeah I actually want to update this act this variable so I'll make it a reference to that variable simple okay if we were going to use pointers for this one then and to be quite honest if you think I don't want to know if this is good enough for you you can just skip the next bit of the video press the all right button on YouTube and it will zo it along uh but I'll tell you about pointers just so that you can recognize what we'd have to do to this to make it work with pointers we'll pretend C++ doesn't really exist as you can see the code on the screen is currently set up to allow references so these ends up here turn these declarations here from an integer to an integer reference fine okay let's undo that and see what we've got to do now to make this uh use pointers which as we said are well as the name implies they're just memory location somewhere in my 32 gig ram it goes that one there and that one there and pointers are always well in our world anyway two bytes they are in fact integers themselves that's sort of irrelevant really so when you see a declaration for a pointer don't start thinking we're describing the pointer a pointer is a pointer is a pointer you don't have to describe that you're saying the thing I'm declaring now is is of this type so look up here we can say not a reference we can say an integer pointer yes the asterisk hrah so an integer pointer which does not mean the pointer is an integer because he's that's beside the point we're declaring a variable a a as an integer pointer in other words it's pointing to a variable that is an integer and I guess that way it knows that it's two byes long as well yeah so if it is it that easy can we just put a little little asterisk in there and go hey we've done it like we did references no of course not as you can see already we're getting squiggles here under the a squiggles here squiggles down here in the calling because it's the wrong type yeah we've said now this function has been defined to say I want a pointer to a variable not an actual variable itself and yet you've coded it as though it were a variable that's all nonsense go away and fix it okay let's fix it then now one of the main problems with pointers is that they use two symbols the asterisk as you've just seen and the Ampersand and they mean different things depending on where they are in the code so you see an asteris you go oh that's an inj your pointed decoration no it isn't always the one I've just done up there most certainly is we're saying this is an inur pointer called able a this is an injur pointer called double b yeah what's what's that you've seen it written differently to that what do you mean oh the spacing all right let's let's address that as well as we're talking about pointers you might find this written as integer space asterisk doubleb or integer space asterisk Double B like that yeah three ways of writing it none of which are wrong but in my view what you're saying and which is why write it the way I do is that this isn't this is not an integer of a pointer BB this is an integer pointer to a variable called BB yeah which is which is a little bit different Hello what have I touched there we are all right so that's why I put the asterisk next to the type that I'm declaring so an integer pointer or a character pointer or whatever it is yeah it's not wrong doing it the other way but just makes it in my view clearer this way yeah I know there's probably 50 people screaming at the screen right now saying you done that wrong anyway let's move on now to get all this swapping around obviously we got to get the value that the pointer is pointing to yeah we've got the value of the pointer itself the memory address now well we will have when we' fixed it all so when we say int temp equals AA well we can't do that can we because AA is a pointer that's right it's not a value anymore to get the value of the thing the Pointer's pointing to you've got to put an asterisk in front of it like that now what that is is D referencing the pointer yeah it's another another term for you to throw at your uh nearest party or get together oh yes I've been doing lots of D referencing today you know but that asterisk this is the important thing that asterisk is not the same as that asterisk up there which is well I'm a little bit disappointed really in see itself why they happen to use the same symbol yes they're related obviously because they're all talking about pointers but why not use something like a a carrot sign you know the Hat above the six is it yeah you know just to make it absolutely clear to people what it is you're talking about I guess it's the way it is and we have to live with it so what we're saying here then is int temp is equal to the value the underlying value of whatever's pointed to by the pointer a a great okay that's worked the next line though is a bit problematic it hasn't complained about it but that's never going to work what we're saying here is the pointer AA because we know AA is a integer pointer because we' declared it up here is now equal to the pointer BB that's nonsense isn't it if a was pointing to a variable and address hex df1 123 we now saying a a is now pointing to the B address of XY Z 496 over there yeah that wasn't hex yeah I forgot it's nonsense so to do this what we're trying to say is the value pointed to by AA is equal to the value pointing by BB okay that's fine and then we're going to say the value of bb is equal to Temp now temp is just a standard integer it's not a point or anything it's just a standard value yeah because we declared it here and that's what we're saying the value of the pointing thing here BB is equal to Temp there we are so what we've got here then is a mixture of asteris up here and then asteris down here which are not the same as the ASCS up here they mean something else here they're all dereferencing things and here they're declaring the type that you're pointing to you're saying this is an integer pointer yeah here you're saying I want the value of D reference this pointer and give me the value yeah I I knew I shouldn't have started this video it's just anyway that's not the only problem we got is it down here look swap AB it's saying squiggle squiggle and that's because we're passing in to this routine at the moment we're passing in an actual value of a and b it goes hang on that's that's not what I'm expecting I'm expecting a pointer aren't I and you've not given me a pointer so that's syntactically incorrect how do we pass in a pointer to a value or a variable here well you've seen it once but it's it's sort of different in a way to do this we say swap the variable located at a particular address and we use the ampersand and did so we'll have to do that for b as well so what this is now saying yeah I know I know we're saying swap uh the value pointed out by this address and by this address A and B and when this gets called over here swap is saying oh good you give me a pointer of one variable and you give me a pointer of another variable that's fine I don't know what the values are yet because you've not asked me to look at them and then we get into the code and we say temp is equal to the value of the pointer pointed to by AA because we put a d referencing asterisk at the beginning and then we get the value of AA and the value of BB and assign it to AA so whatever AA is poting to now contains the value of BB and BB then becomes the value of whatever temp was it's exactly the same logic as what we just had but there's lots of asterisks and ampersands and all sorts of things going on here let's let's just run this and see if we get the the same results as as we did down here um fingers crossed he Let's uh let's have a look might not even compile let's have a look oh look at this it can't find the specified path this is a problem with Visual Studio actually rather than anything else there we are right oh that's interesting oh yes of course we've got one didn't we right let's walk through these results shall we we're saying right before we did the swap a is five and B is 10 just as it always inside the swap we're saying a is equal to this big long heximal number and B is equal to this one why is that do you think cu the the output here is saying AA is equal to AA and what is AA well it's an integer pointer and did say BB is an ingry pointer so what we actually printed off here is the actual pointer value which isn't really useful to us to look at is it um but it does prove that it is a point of value so we've passed in the point of value fine but behind the scenes we've grabbed whatever they're pointing at because when it comes back out it goes look a is now 10 and B is five so it has swapped them over yeah that's what we wanted but oh my just just look at that code all the asterisks and Ampersand and everything else just to make a simple little switch of a a variable compared to using references yeah um let's think for a minute the advantages of using this method against using the reference of a single Ampersand let's let's just have a little think about that because I'm sure if I think long and hard enough I'll come up with no no at our level definitely not okay I know that yeah experienced programmers will say well I want to do a bit of memory management myself and create variables using a pointer and grab the memory and keep it by using the new keyword but even that has now been superseded in C++ say well look if you really want to do that within your function like swap if you wanted to create a pointer to a bit of memory that you're just working on and you want it to exist after the function has ended down here don't use a pointer use a Smart pointer because a smart pointer will manage that memory and get rid of it into the ether when nobody's using it anymore but I'm not going to cover smart pointers we don't need those highly unlikely highly unlikely I think I've used them once or twice in my entire work on Arduino esp32 stuff we just don't need it but if you want to recreate this little routine on your Arduino or esp32 be my guest um don't get confused about the asterisks here because they're not the same as the asterisks up here and don't get confused about the address of Ampersand here they're not references they're address of so swap the address of a and the address of B yeah similar to but not the same as references I know which one I prefer now it's just worth mentioning at this point that passing by reference instead of by value which is the default um does have some benefits in some situations if you're just passing a simple integer value across it's only two bytes and whether you pass it as a a pointer a reference or as the value itself makes no difference at all to the speed of your program right even if you're passing you know 20 Ines across it's just trivial however if you're passing a huge big string across yeah let's let's say a th000 bytes then that most definitely does matter because if you're passing it by value then it's got to copy those thousand bytes into another bit of memory and pass that across yeah now the Thousand bytes of course is somehow got to fit in your memory for a start and then there's a Time taken to copy all the Thousand bytes across however how often did we pass a thousand bytes across to a function not very often and if you're thinking hang on a minute I've got a couple of arrays that I I move about and do stuff well the bad and good news I suppose is that in C++ arrays true arrays um are passed by point of value anyway not by value in fact the first element address is pass to the function um and that's all it knows it doesn't know how long the array is on anyway which is another good reason not to use arrays in C++ use vectors vectors can be passed by value or reference exactly the same way as we've shown in this demo here so really I guess the point I'm making here is don't worry about um the cost of doing all this if you're using C++ properly and you should be then it's a no-brainer and you just pass it either by value or by reference and ignore pointer I'll say it again ignore pointers don't use them please okay that's it I think we're done here as far as references and pointers are concerned you've had a look at the pointers you've seen how complex it can be not for the faint-hearted and in fact not for us C++ programmers either use references that are simple to do and are normally in the calling called function that you declare the reference and your calling program doesn't really know whether you've got a reference or a pass by value parameter yeah it doesn't really matter does it the point is it's easy to do and abstracts all that complexity away now if you think no Ralph you're wrong pointers have got a very valuable place in C++ and I'll tell you for why good tell me for why in the comments and if you start talking about creating new variables like a new integer or something I shall I shall delete your comment or put something rude on it yes I will indeed because we are not in that ballpark for beginners learning about references and pointers okay I think we're done don't forget if you like this sort of stuff yeah do give me a thumbs up hey yeah and if you want to subscribe if great that' be lovely to have you subscribed to my channel and don't forget what else you got to do that's right you got to tick that Bell because otherwise you won't be notified of any future videos that would be sad wouldn't it so in the meantime see you in the next video I hope you're finding these videos useful and interesting there are plenty more videos to choose and a couple are shown below and if you'd like to subscribe to this channel just click on my picture below and enjoy the rest of the videos thanks for watching
Info
Channel: Ralph S Bacon
Views: 5,896
Rating: undefined out of 5
Keywords: Arduino, Beginners, electronics, C++, microcontrollers, programming, gadgets, ardiuno
Id: jdQaaFNpM_4
Channel Id: undefined
Length: 31min 46sec (1906 seconds)
Published: Fri Dec 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.