When do I use a union in C or C++, instead of a struct?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're talking about the difference between unions and structs and specifically when you would want to use unions [Music] welcome back everybody today i wanted to do a beginner kind of c basics video that's inspired by quite a few questions that i've gotten over the last few years about unions what's a union what's a struct how are they different when would you use one over the other so that's what we're going to talk about today this video will contain source code source code is available as always through patreon a big thanks to all of you out there that support this channel i couldn't do what i do without you so that said let's jump into the code okay so today i want to start with a really simple program just your typical hello world type program except there's no hello world in here um i do have a quick make file here which will just compile my code it's pretty generic and what i want to look at specifically is the difference between structs and unions and so let's just make one of each so i'm going to use type defs here you could just normally just so just normally if you're making a struct you would say struct something like this and then you put the elements in here now if you do it this way you have type struct every time that you refer to this type and i don't like doing that personally so what i'd like to do is to say type def and then move the name down here what this is doing is it's saying it's making a struct and it's type duffing that to my str so anytime i say my str i don't need to put the struct beforehand and it's already defined as a struct so now inside here we can put let's just go through and make a couple of members so let's have an int called x and a float called y and a character called z okay now when you define these things it's no mystery that people get a little bit confused between unions and structs because basically they look a lot alike you know really the only thing i'm going to do is change this struct up here to union and then let's change the type down here to my union okay so these look very similar they only vary really by this one key word one's a struct and one's a union so what i want to do today is to talk about how these things are the same and how they're different so obviously their syntax is very similar they have members they can have members of different types so that's great in that way they're the same but to understand the differences let's first jump down here into main and let's just print out let's print f let's print out sorry it needs to be unsigned the size of each of these okay so let's do size of our struct i'm going to say struct size and then let's come down here and do the same thing but with our union and let's just come down here we'll make it and we'll run it and so the first thing you can see is that the struct is much bigger okay the reason and the fundamental difference here that we want to talk about is that your struct has room for all of the members okay the union on the other hand basically assumes that you're going to store one of these members but not all of them and so they really it has three members sort of at least you can refer to its x member and its y member and a z member but they're all stored at the exact same location in memory okay so that's why even though you've got an ant which is four bytes a float which is going to be another four bytes and a char which is one byte usually the whole union is still going to be just 4 bytes rather than giving you 12 like we get with the struct now some of you may be wondering why did we get 12 with the struct why didn't we get what four plus four plus one why didn't we get nine and that comes down to struct packing and that's a topic that i covered a little bit in another video so you know check that out i'll put a link in the description but before we move on just just in case you're not sure exactly what i mean here let's let's print out a few things let's just play around with this for a minute so let's come down here and create a new struct let's say meister let's call it s and then we're going to say s dot x equals let's say 45 s dot y equals 9.87 and s dot z equals the letter h okay pretty straightforward let's do the same thing with our union so i'm gonna make this so my union we'll call this one u and then let's just do this exact same thing we did before u u and u okay so we're basically doing the identical thing now as you would expect this is probably going to work differently so because the struct has room for all of these they'll stay separate because they're all being stored in the same location in the union we should expect to see some funny business when we do this so just to make sure let's print f and let's say i want an int i want a float and i want a character and then let's just do s dot x s dot y and s dot z okay and let's do the exact same thing with our union notice our syntax didn't really change we're treating these again exactly the same but let's just see what happens when we try to print these out okay so when we try to print these out well things do go a bit haywire so you notice that our letter h is still fine because that got stored last it's basically one byte and nothing got a chance to overwrite it the other two got a little bit messed up so the first one got seriously messed up because the bites of both of the following two elements overrode it and then the middle one seems like uh it's hard to tell if it got how much it got messed up um i probably just got some of the some of the low order information got messed up and so it's slightly off but not bad okay so this is cool now you understand sort of the differences between structs and unions but why would you use a union why do you want something where you've got a bunch of elements that you can refer to but they clobber each other because they're located in the same location in memory so that's a problem and it may seem pretty pointless and to be fair i don't use unions nearly as often as i use structs structs seem to be used all over the place unions not so much but let's take a look at why we might want a union let's say that i want to make let's say i'm making a struct usually when i use a union it's inside a struct so let's say that i'm making a new game maybe it's a game maybe it's a story something whatever it's got characters right so so i'm making a character yeah so i'm making a character struct and each character in my software whatever it is is going to have different features let's say that we have a name for example and let's say that we have some boolean value that tells you you know is it a robot okay and then maybe here maybe there are two different things and like if it's human we want to know something about his personality and if it is a robot we want to know something about the software running on it because that's kind of the equivalent of a robot's personality well one thing we could do is we could just store two different things right i could say i want to know personality right and that would just allow me to then store a string that describes the personality of course it doesn't have to be a string it could be a struct if you want to store complex information about personality but then i can also say i want some kind of integer that is going to be the firmware version now the interesting thing here is that firmware version doesn't make any sense for a human and personality doesn't make any sense for a robot well maybe it does that depends on how you think about robots and maybe they have personalities some movies they definitely have personalities but let's assume for now that it doesn't make sense to give them personalities but instead we want to specify their software version well if i use a struct like this i'm storing all the information i might ever need and i'm never going to use all this information so i'm wasting space okay so instead what i can do is i can come in here and basically just create a union of these two i notice i'm not even giving it a name here i could give it a name if i wanted but i'm not going to but now what it's going to do is it's saying i have these two things i can refer to but they're going to take up the same memory meaning basically that my character is going to have a personality or a firmware version but never both okay and this allows me to do things like let's come down here and i could make a function called print character and then we'll just pass in a pointer to a character call this character c and then we're just going to print out let's say every time we print out a character we're going to say character and we're going to put its name and then yeah let's stick stick the name in here and then here we're just going to say if c is robot okay so if we're dealing with a robot then i'm going to print f the version and just an integer here and we're going to get the robot's firmware version okay now if we are human oh i should spell this correctly then what we would do is just in this case we're just going to print out the personality and so this is going to if it's a robot it's going to print out one if it's if it's a human or some other creature it's going to print out the personality and otherwise it's going to print out the version number so and then let's just put down since for all of them we're going to want a slash n at the end to just end the line now this is going to be just sort of a general print character function that allows us to treat characters in a generic way elsewhere in the program but it handles each of their individual quirks inside this function so now let's come down here and i'll just leave this as is let's just add to the bottom here and let's make a couple of characters okay so let's make han solo and let's make another character who is r2d2 yeah this is gonna be a fan fiction piece i guess and han solo's name is to be han solo and han solo is not a robot at least not that we know depending on how far disney takes this franchise that might come out in the next one but let's give him a personality which is a scruffy looking nerf herder i think that accurately represents him now let's say r2d2 name is we'll just say r2 for short and then r2d2s is robot is true and the firmware version is uh 42. that seems to be a favorite number on this channel now we can just come down here and print our character and we're going to print out on first and we're going to print out r2 right here okay now note that this would all work exactly the same if i was working with a struct wait what did i forget oh i forgot an amberson okay so this would all work the same if we were dealing with a struct but in this case we're just going to use less memory right so it still works we're still able to handle our little droid and our scruffy looking nerf herder but the key here is that using a union versus a struct in this case the union is going to use less memory because we're not actually allocating enough memory for both a personality and a firmware version we're just allocating enough memory for the largest one and so if i'm creating a lot of these characters this is going to save me a lot of space so folks that's it i hope that helps illustrate the difference between unions and structs hope this is helpful in your future projects help you save some memory like the video if it was helpful subscribe if you don't want to miss the next one and until then i'll see you later
Info
Channel: Jacob Sorber
Views: 67,795
Rating: undefined out of 5
Keywords:
Id: b9_0bqrm2G8
Channel Id: undefined
Length: 11min 17sec (677 seconds)
Published: Tue Jun 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.