#BB7 Pass by Value or Reference - What's the difference?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and welcome to my series of short videos in which we discuss how the arduino interacts with various electronic components yes in less than 15 minutes we'll go over the basics how they can be used hints tips tricks and traps now passing variables into a function is just taken for granted really but do we actually understand what's happening at the point of passing that variable into a function well this was brought to mind recently when i was playing about with this device here which is my storage bin monitor uh out the back that i've got three identical units like this this one's in here just to aid with my testing for the thing on over there on the wall and i made a very simple mistake and i thought what's going on why isn't this being updated and of course the answer is because passing by reference and passing by value are extremely similar and sometimes it's easy to make a mistake so i thought hmm maybe this is something i need to tell you guys about so let's let's think about a very simple piece of code and we can have a function or two that accept parameters in and let's see how they're passed i want to do a shout out for jlc pcb no stop stop don't go away look what they're doing two dollars for aluminium circuit boards this is absolutely incredible if you've ever wanted to try an aluminium pcb now's the time to do it now remember aluminium pcbs are single sided normally with the aluminium on the bottom then you have a dielectric layer that transfers the heat up to the top copper layer now aluminium is very very strong and it will suck the heat away out of your components without the need for extra heatsinks for example go and have a look at their website and check them out and there's more jlcpcb now allow you to create your own parts library because there's nothing more disappointing than creating a pcb and then finding you can't get the parts or there's a big long delay now you can create your own custom parts library to ensure you get the components you need and of course the associated footprints so you know they're going to fit on the pcb itself to get to this page that describes everything you ever need to know about creating your parts library simply go to their home page and then click on the link at the top very very simple and a really really useful feature go and check out jlcpcb now so here's a very simple little bit of code it's yes it's demo code so it doesn't do a lot but it shows you the difference between passing variables by value and by reference so let's just whiz through this um i am using the library lib print f here to give me the print f facility within the arduino environment that isn't there normally yet yes you get it with the esp32 and the 8266 by default but not with the arduino but by using that library here that i did go through in some detail in there that video it just makes life a whole lot easier and stops you having rooms and rooms of serial.print statements okay so that's what we're going to be using here just to illustrate a point or two right so first of all what's on this line here well this says integer int one equals one and yes global variable and as you can see there's a little very annoyed face there because i don't like global variables unless there's a very good reason for having them and the very good reason in this case is just to keep it out of the way so it doesn't clutter up the demo code here but normally i wouldn't be using it like that but that's a little integer into one and we've set it to one and that's what we're using as part of our little demo the setup does nothing other than to initiate the serial output so nothing to see there this little function here pass int by value well we'll be looking at that in just a minute but let's have a look at the loop first so what we're saying is if we look at line 29 we're saying the result of the call to pass int by value yes that one up here that we just looked at using int one as the parameter yes that global value there is uh printed out here in fact but what do we actually mean by pass int by value into one yeah int one happens to be a two byte integer and its value initially certainly is one and we're passing it to this particular function but what happens you know in the background what does the compiler do well it goes great you want me to pass an integer to that function over there i'll take this integer i'll make a duplicate a copy of it and give that to the function to do what it wants with it's a bit like if you have to prove your identity you might take your passport somewhere and you go to some official place and you go here i am and here's my passport but of course the last thing you really want to do is give up your passport so they say great i've seen the passport i can tell it's a real one and i've looked through it that's great i'll make a copy a photo copy of the relevant page inside and you keep that passport i don't want it anymore and i'm not going to touch it so now they've got a copy of that passport and they take it away and do whatever it is they like with it but whatever they do with it it doesn't affect your original passport does it and that's exactly the same as what happens here where it says past int by value int one we're taking a copy of that integer a duplicate and yes that is two more bytes that the compilers are going to stick onto the the heap for you copy the value into it and then pass it to that function that you can see that it says int pass by value so let's have a look at what that does so it accepts this integer value here the copy of the parameter you passed remember not the original it adds one to it with this statement here a little bit long hand but let's keep it simple so my int becomes equal to mind plus one so we've incremented this value and we're returning my int by this return variable here so pass into by value function returns an integer as its response now you might say ah but hang on my int has now been incremented so surely this value has changed and it has my int has indeed changed otherwise it wouldn't work but the original parameter that we passed to this function down here as int1 into one has not changed because that was the original value and we haven't changed that we're passing by value a duplicate copy of that in this case integer fine and we can prove that simply by these two printf statements before and after we can say int one is equal to whatever value it is and into one after the call is equal to something as well and the result of this function here where it should add one to the value being passed in is returned and printed out here so the return value which we're capturing as part of this result variable is being printed out here so what do you expect to happen then so initially it's set to one so we're saying well before the run the call it should equal to one then we're passing it in by value and it's doing whatever it does with it and we're capturing result and after it comes back this int one should be unchanged it should still be one but the result of course will be one more and that's what we expect to see here so it should be two hmm should we give that a run then see what happens right let's bring up the debugging window and have a look at that right so i've connected to it so we should see right the setup's completed and then it simply repeats this little block of information forever and a day so let's disconnect that and see what it's actually doing so let's roll back up to the top so we say before the increment this is the very first time it's been called int 1 is equal to 1 as we'd expect because after all the code over here sets it to one okay and then it says after the increment it's one again so regardless of the fact that int one has been incremented within that function the value in this function here the main loop it hasn't changed because it was a copy that we passed across cool we understand that and the result of this call where it should have added one and it has done and returns it is what we get over here so from the function the result is two great now because nothing has changed it just keeps calling the same thing over and over and over again we just get this block repeated add in item hmm okay now you might think what's the big deal well sometimes it's extremely useful and indeed necessary depending on what it is you're calling to pass something by a reference if you're passing something by a reference it's basically pretty much like somebody pointing to something i'm not going to use the word pointer here because we'll get onto pointers at some future stage but what we if we were to pass this value in here by reference it means we're not making this duplicate copy and then stuffing the values in there and going off you go it goes here in memory is the variable and that's what we're referencing in the function which means we can update it hmm let's change that particular function then that we're currently looking at to say how do we pass things by reference then and what's the big gotcha about passing things by reference so here's another function that i've written and it's called pass int by reference int except of course you'll immediately see there's the little ampersand there to say by reference that's exactly what that ampersand means in this particular context so it's a reference to an integer because it says int reference my int well you can call it what you like doesn't matter now when we add something to my int now from here to here that actual value that has been passed to us is being updated it's the single value in memory so if you look down into the loop area now where we have our second call pass int by variance int one we should see a difference between the value coming in here and the value being returned here so it will go in as 1 and it will come back out as 2 because this lets us update the actual underlying memory because this is a reference to that memory not a copy of the value now i've left the original one in just so you can see the difference you'll see the interaction that passes by reference here to something that passes by value up here so let's fire up the debug monitor and start this going right there it is so now we have several iterations so let's stop that again and scroll back up to the top so the very first time which is this one down here this bit here that it where it runs we can see at the top there that would go in as one we come out as one and the result from that function is a two exactly as we always had it this bit here but the next call to this one here it says well before the increment it was one but afterwards it's now two we've actually updated the underlying memory value now this is sort of a double-edged sword isn't it really do you want the value that you're passing into a function to have the power to fiddle about with that value what if you're passing a sensor value that you've been given into a function that then changes that value now it might be you're changing it from fahrenheit to centigrade so you throw fahrenheit at it and you get centigrade back whoa great that's what you want uh but what if you didn't want it if you think that no i don't i don't want you to change the underlying value of what i'm giving you i'm just giving it to you as a value to get on with and work out some other stuff or perhaps logs to the cloud you don't want it changing anything so that's where pass by value which is the default method of passing anything to a function comes into its own something where you want a function to take the value coming in and not play with it but if you do want that value to be updated or converted or incremented or whatever it is you need done done to that value you pass it by reference and the very easy way of doing it is just in the code your function is just to put an ampersand either next to the int or the mayan there's a big school of thought about exactly where that ampersand should go but it doesn't matter and there we are pass by reference now there we have a gotcha what happens if the function you're calling is in fact a library function that you don't really know much about yeah you're updating i don't know an lcd or you're calling something to update something else in in the cloud some function that you really have no idea about you don't know easily whether the function you're calling is a pass by reference or a pass by value and it may be prudent just to find out which one it is because if unknown to you it's a pass by reference and it can update that value that might not be what you want at all so just be aware that a library function could be doing this without even you finding out because you're calling it here from the loop without even understanding what's going on in the background in that black box of a library hmm tricky now we did mention right at the beginning there could this also be some kind of pointer than this reference because after all if you're passing by reference the reference is by very nature pointing to the actual memory location that you passed in yeah it's not a copy it's the actual one but and surely a pointer then is something different to a reference and in c plus plus the rule is pass by reference where you can and by pointer if you must and by must it means if you are calling perhaps a library routine as i was with my little esp32 project going on there quite often you pass by pointer because you can't do it by reference and yeah you need to understand that you need to pass it a pointer not a reference we'll be talking a lot more about pointers and how they really work when i finally get to the pointers bacon bites video it's it's easier once you get your head around it but all this reference and value and pointer talk just makes it sound more complicated than there is good for dropping into the conversation about your next soiree right i'll put the code up into the github few other pointers pun intended and i'll see you in the next video and it might even be about pointers 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: 13,511
Rating: undefined out of 5
Keywords: Arduino, Beginners, electronics, C++, microcontrollers, programming, gadgets, ardiuno
Id: nVIT3972mIc
Channel Id: undefined
Length: 16min 35sec (995 seconds)
Published: Fri May 06 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.