the cleanest feature in C that you've probably never heard of

  Рет қаралды 120,922

Low Level Learning

Low Level Learning

Күн бұрын

You've heard of structures, you've heard of functions, maybe you've even heard of the C preprocessor. But, have you heard of unions? Unions are a weird type in C that don't get a lot of love. In this video we'll discuss what a union is, how unions work in memory, and wether or not you should use unions.
🏫 COURSES 🏫 Learn to code in C at lowlevel.academy
📰 NEWSLETTER 📰 Sign up for our newsletter at mailchi.mp/lowlevel/the-low-down
🙌 SUPPORT THE CHANNEL 🙌 Become a Low Level Associate and support the channel at / lowlevellearning
Why Do Header Files Exist? • why do header files ev...
How Does Return Work? • do you know how "retur...
🔥🔥🔥 SOCIALS 🔥🔥🔥
Low Level Merch!: lowlevel.store/
Follow me on Twitter: / lowleveltweets
Follow me on Twitch: / lowlevellearning
Join me on Discord!: / discord

Пікірлер: 478
@CoolestPossibleName
@CoolestPossibleName 5 ай бұрын
I discovered union when I tried to name a function union
@mingy7949
@mingy7949 5 ай бұрын
I discovered it from dwm
@stapler942
@stapler942 5 ай бұрын
I think I learned about unions from some book when I decided to learn C. Two keywords that are probably even more obscure are "register" and "volatile".
@AustinClemLive
@AustinClemLive 5 ай бұрын
This is how I discovered the "register" type modifier
@MorRobots
@MorRobots 5 ай бұрын
Such a relatable thing 😆
@filipstojanovicmechanicale9265
@filipstojanovicmechanicale9265 5 ай бұрын
I discovered register keyword when i tried to name some sensor register as "register"
@eduardobarreto6116
@eduardobarreto6116 5 ай бұрын
unions are also very useful for dealing with communication packets, where you have a byte array that represents your entire packet, along with each item present within it. This way you can access the entire package (to send to other parts of your program), as well as each separate item
@TheCarmacon
@TheCarmacon 5 ай бұрын
This is the number one usecase for unions - they're widely used in embedded programming when communicating with peripherals, especially if sensors or FPGAs transmit differently sized junks of data. Unions are very useful when the developer of the peripheral didn't/couldn't give a shit about consistency.
@eduardobarreto6116
@eduardobarreto6116 5 ай бұрын
@@TheCarmacon I don't know if I understand your last point about consistency... consistency in communication can be achieved in other ways such as validating the package in N ways before reaching the union... Did you mean anything after that? Like any conversion problem? I would love to know more about it
@0xDEAD_Inside
@0xDEAD_Inside 5 ай бұрын
I need an example of it. Can someone show me some demo code to understand how it works?
@BacklTrack
@BacklTrack 5 ай бұрын
that's the only time I've used em
@GoofyChristoffer
@GoofyChristoffer 5 ай бұрын
This is exactly what I've used unions for in communications between two embedded processors
@mk72v2oq
@mk72v2oq 5 ай бұрын
The last thing is actually a very old concept called discriminated unions. Primarily used in functional languages, it was buried for years during OOP languages golden age, where it is effectively was substituted by inheritance. More modern languages are bringing it back though, in light of recent tendencies where inheritance is considered a bad thing. Like Rust has native support for discriminated unions via its enums, TypeScript has them too etc.
@naomicoffman1315
@naomicoffman1315 5 ай бұрын
Recent versions of Java support them as well, along with growing support for pattern matching.
@jacobzimmerman3492
@jacobzimmerman3492 5 ай бұрын
The only issue with C unions is you don't get the same compile time checks, which are a big part of the safety/refactorability of algebraic data types
@alexmiller3260
@alexmiller3260 5 ай бұрын
I think there is no connection to a bad OOP, obviously because even non-OOP languages mostly support basic features like dinamic dispatch through interfaces and type erasure or even allow you to make manual inheritance with pointers. d. unions are just way better sometimes. in Rust ranges Option drops hasnext() function to get next element of a collection
@lucass8119
@lucass8119 5 ай бұрын
Sum types like you describe allow polymorphism, just like inheritance and interfaces. The problem, or maybe benefit depending on the circumstance, is that it is closed-set polymorphism. All possible concrete types must be known and specified at compile-time. You can't simply create a new type and then conform to an interface - you must go back and modify the original sum type. This can be cumbersome. Consider Rust, modifying an enum ALSO requires modifying ALL match expressions associated with it. The code change is much larger, and you *might* have to modify stuff you don't want to or aren't allowed to.
@ahG7na4
@ahG7na4 5 ай бұрын
pascal calls them variant records
@stapler942
@stapler942 5 ай бұрын
They say big corporations employ people to go into their repos and replace all C unions in commits with other corporate-approved solutions. They're known as "union busters".
@DavidLindes
@DavidLindes Ай бұрын
Hah. If only union busting was as relatively benign as that... alas.
@locutusofborg
@locutusofborg 5 ай бұрын
I have been programming for over 20 years and yet while I knew about unions I never used them. Just goes to show that an old dog can learn new tricks. I love how you really explain the low level side of things. Keep up the great work!
@ThePC007
@ThePC007 5 ай бұрын
Did you just never need one or did you just cast between different structs, instead?
@locutusofborg
@locutusofborg 5 ай бұрын
@ThePC007 I never really understood them and equated them with a struct so just used structs or more commonly classes as most of my programming is in C++ (Qt/C++ to be exact)
@VersDarkmoor
@VersDarkmoor 5 ай бұрын
When you are doing any kind of protocol, you basically want to use unions. You basially switch case on the opcode ie. first byte and then interpret the incoming frame accordingly. If you don't want to use unions for some reason, you can always do explicit type casting, which is not great.
@ayaya-ayaya
@ayaya-ayaya 5 ай бұрын
@@VersDarkmoor In my experience we just use explicit write32_be/read32_le and friends to read out protocol fields. Casting unions/structs onto serialized data is a recipe for disaster once you build for a different microcontroller CPU.
@macchiato_1881
@macchiato_1881 5 ай бұрын
@@VersDarkmoorthat sounds really dumb and unsafe
@TheKoga25
@TheKoga25 5 ай бұрын
I used it while making my gameboy emulator, it helped a lot for mapping the CPU registers easily and in a lean way. The data inside some of those registers can be 8 bits (high or low part of a 16bit data, the A, B, C, D, E, H, L registers) or 16 bits (when combining two 8bit registers, the AF, BC, DE, HL), it's a neat feature.
@Hauketal
@Hauketal 5 ай бұрын
But not portable due to endianness and alignment issues unfortunately.
@giorgionegro5750
@giorgionegro5750 5 ай бұрын
@@Hauketal you probably can use some preprocessing to make it at least compilable for all endianes
@Hauketal
@Hauketal 5 ай бұрын
@@giorgionegro5750 Oh, it is always compileable. But the result will be buggy, if you e.g. push BC onto the stack and then pop B and C separately. There is no standard header known to me to generate different code, except the one for the Linux kernel. But one can check at startup if the assumptions were correct. Like union { long a; char b[4]} u; u.a = 0x12345678; switch (u.b[2]) { case 0x34: // little endian; break; case 0x56: // big endian break; default: // weird, PDP-11 had 0x12 here }
@williamdrum9899
@williamdrum9899 4 ай бұрын
union reg_af{ unsigned char a; unsigned char f; unsigned short af; } Should be fine
@protonmaster76
@protonmaster76 5 ай бұрын
I use unions in embedded programming as you described. An other trick for mapping a register to a variable is bit fields where you can make members of the union take a defined number of bits.
@m1geo
@m1geo 5 ай бұрын
This - so useful!
@electronlabs2802
@electronlabs2802 5 ай бұрын
Almost all embedded c developers know it :) ..
@slartibartfasttynsol420
@slartibartfasttynsol420 5 ай бұрын
Converting between types (such as the IP example) is called 'type punning'. Historically it has been poorly defined in the C standards, but does work in gcc C and C++ via a documented extension. The draft C18 standard does clarify the situation, and explicitly allows it. Note: You need to be careful with endianness - the uint32 representation of the IP address would be different based on endianness, so there are portability considerations.
@user-zk6rg5jz6b
@user-zk6rg5jz6b 5 ай бұрын
It is worth noting that this is explicitly allowed only in C. It is an undefined behaviour in C++.
@lucass8119
@lucass8119 5 ай бұрын
@@user-zk6rg5jz6b Only technically. Its well-defined in all 3 major compilers via extensions.
@EarlHutchingson
@EarlHutchingson Күн бұрын
Yeah there's too much undefinedness circling around unions. This video is fairly bad teachings.
@KillerSpud
@KillerSpud 5 ай бұрын
I use unions to pack 8 byte CAN messages all the time. Its also very useful when using bitfields as well, instead of checking eight or sixteen individual bit flags, you just check to see if the entire thing is or is not zero.
@xhivo97
@xhivo97 5 ай бұрын
i hear this all the time, but I don't understand because I thought a lot of this is UB or something like that
@feeditehh
@feeditehh 5 ай бұрын
@@xhivo97 its probably technically undefined by some strange wording in the standard, but in practice it works fine everywhere.
@KillerSpud
@KillerSpud 5 ай бұрын
@@xhivo97 yeah your code might not be portable, but in all my applications so far it didn't need to be. It could break if one system had a different endianess.
@shauni_jade
@shauni_jade 5 ай бұрын
Exact same use case for me, very useful to separate controller ID from data and checskum and so on
@aidanbecker9758
@aidanbecker9758 5 ай бұрын
​@@xhivo97 The bit-ordering is what's undefined here. AFAIK you can't even rely on tests for endiannes, so you need to test bitfields on a specific compiler/processor if you want to support it. As @feeditehh said in practice it works fine most everywhere, but that next microprocessor that comes out might just find it more efficient to do things in the opposite order.
@lorensims4846
@lorensims4846 5 ай бұрын
Every book on C programming I've ever used had had a section teaching about "structures and unions." Now, I've rarely ever used unions, but I appreciate how it can give your program an alternate view of your data. I can think of several interesting ways to use this feature, but very few practical ones.
@m4rt_
@m4rt_ 5 ай бұрын
I use unions all the time. They are really useful. I use it when writing a Lexer/Parser. (Though I use it other times too, it's just where I use it the most) e.g. typedef struct { uint32_t line; uint32_t col; enum {IDENT, NUMBER, STRING} kind; union { struct { char* data; uint32_t len; } string; uint64_t number; } } Token;
@LogicEu
@LogicEu 5 ай бұрын
Unions are great! It's extremely useful to be able to interpret a single piece of data as different types, structures or even arrays. Say you have a 32 bit pixel representing RGBA channels, sometimes you may want to access individual channels with their own unique names as you would in a struct, sometimes as raw byte arrays and maybe sometimes you want to simply assign a 32 bit value to the whole pixel.
@masondaub9201
@masondaub9201 5 ай бұрын
I've used unions for some embedded stuff but most of the time I just end up using a bunch of bitwise operations instead. Never thought about using them for polymorphism though, that is actually pretty cool!
@CamaradaArdi
@CamaradaArdi 5 ай бұрын
Cool - and dangerous. The compiler doesn't give any guard rails, wouldn't recommend trying at home
@dliamk
@dliamk 3 ай бұрын
@@CamaradaArdi Got it, I'll try on the prod environment instead 🗿
@homeopathicfossil-fuels4789
@homeopathicfossil-fuels4789 5 ай бұрын
I learned unions quite early in my C language learning process, I find them extremely useful for all the cases you stated here and more. For making VM's for in development hardware and domain specific languages they are a godsend, also comes in handy in game engine programming, hell my yet to be uploaded codebase for a dead simple and easy to use and maintain forth with readable code and a focus on being embeddable in applications as a lua replacement uses that. Speaking of which, I got a video suggestion: Forth! It has seen its fair share of use in embedded systems.
@LaserFur
@LaserFur 5 ай бұрын
For type punning be sure to use pragma push and pragma pack. Then also add a #if defined processor name to make sure that if the code is compiled for a different processor the endiness can be checked. For C++ the language labels it "undefined behavior", but most compilers have a defined way it is handled. C++ lacks reflection so serialization any other way takes a lot of code. With a untion only arrays and strings have to be handled separately. Also note that the structures in the Union can't be a class, but can be an aggregate.
@DavidJohnsson
@DavidJohnsson 5 ай бұрын
I do embedded programming and use unions quite a bit. I think they are very useful, but they have their problems. For instance, if your code is targeting two different platforms with different endianness, then multi-byte unions will give you a very bad day!
@CZghost
@CZghost 5 ай бұрын
This can actually be turned into an advantage, because you can essentially detect endianess this way. **wink wink**
@hymnsfordisco
@hymnsfordisco 3 ай бұрын
The data conversion examples are cool, but it's important to note that they depend on the byte order ("endianness") and memory size of int, which can both change depending on what platform you're on.
@1rssr183
@1rssr183 25 күн бұрын
Short and sweet, really captured the essence of unions, I have never understood it better until now. Thanks!
@TheMasterAbdul
@TheMasterAbdul 5 ай бұрын
I love it because it can make complicated things more easier. I used it as a messaging protocol, where the shared object is a header, with a type, then the buffer after that depends on the header along with crc
@konstantinsotov6251
@konstantinsotov6251 5 ай бұрын
I discovered unions through cppreference And when I was writing my own json parser as an exercise, unions were the core of library's design They are not used really often, but sometimes they are irreplaceable :) Edit: and they are what makes C more functional of a language than python and many other popular ones. Because unions and structs are basically algebraic data types
@YannGREDT-nh8et
@YannGREDT-nh8et 5 ай бұрын
thanks for the tips ! I also use struct of function to make some kind near C++ with C
@lalpremi
@lalpremi 4 ай бұрын
Interesting, thank you for your introductions to Unions. I will experiment with it and understand it 100%
@brianm.johnson4438
@brianm.johnson4438 5 ай бұрын
Hey LLL, can you do a video on how SIMD works under the hood? Because it's relatively new, not many assembly textbooks cover it and how to write programs to take advantage of it.
@xr.spedtech
@xr.spedtech 5 ай бұрын
See anger fog's blog for performance programming.
@adama7752
@adama7752 5 ай бұрын
Under the hood, a CPU has more than just 1 'adder', it has several ALUs. SIMD is aligning those ALUs to do the same thing (add) at once (or double pump). The cost is generally power, and some developer setup to align the data to the boundary (ignoring unaligned simd with intel). In short in assembly the easiest is to do a memcpy. While(addr&0x3) copy_byte(); while(addr&(16-1))copy_uint32(); then copy via simd
@MorRobots
@MorRobots 5 ай бұрын
Gcc flags -O2 -mavx2 will just optimize your program and often will use these instructions automatically
@sinom
@sinom 5 ай бұрын
SIMD was first implemented in a computer in 1966. I wouldn't exactly call it "new". And even the modern variant with SSE was introduced in 1999. Basically all they are is that instead of only using two registers for e.g. an add instruction, you instead first load all the data you want into special arrays of registers which the operations then get applied on. After that you can move out your result
@modolief
@modolief 5 ай бұрын
Yes please; also, how to do it on Apple silicon. I tried some SIMD code on ARM 64 and couldn't get it to work.
@assimilater-quicktips
@assimilater-quicktips 5 ай бұрын
Really well presented video. I really like unions, have used them in some shape or form for most of my embedded programming, although I have a lot of stuff that can’t use them as cleanly as I would like because I have to worry endianness, but that’s just how it goes
@shanehebert396
@shanehebert396 15 күн бұрын
Learned about unions when I was teaching myself C back in the early 80s... have used them a lot over the years... very common in systems and embedded programming, data conversion, and the like.
@ishi_nomi
@ishi_nomi 5 ай бұрын
It is interesting that c can already do so many thing just using struct, while union are pretty restricted to the use case that really make sense. So even if I knew it when I was newbie doing tutorial, I don't ready knew where and how to use it. It is when I once faced a problem that really need union to solve, I really know how to use it.
@peterjansen4826
@peterjansen4826 5 ай бұрын
One of the better KZfaq-teachers. In this case it is quite simple but explaining it at a fast speed without neglecting details is an art.
@QuikRay
@QuikRay 5 ай бұрын
I was doing this union/structure stuff 20 years ago....so powerful...especiall as an embedded C programmer....picking out specific bits of a byte...setting/ clearing etc.
@tempyreuz9469
@tempyreuz9469 5 ай бұрын
I'll be sure to check out the course on the website.
@azimuth4850
@azimuth4850 5 ай бұрын
Always wondered what these were...definitely see how these could save some instructions here and there. Thank you.
@alexjoaquimpereira7671
@alexjoaquimpereira7671 5 ай бұрын
I had come across unions during my first year engineering class, but there wasn't much focus on it, instead all attention was on structures (due to its use in Data Structures). I always wondered why do we need them, and even most websites' explainations of it being useful for type conversion felt silly as I can do it normally using format specifiers. But this is the first time I found the actual practical usage of them. Especially the polymorphism part, which can be used during some DS experiments involving conversion between postfix, prefix, infix operations.
@MeisterJager90
@MeisterJager90 5 ай бұрын
But my sociology professor said unions help undermine class structure 😵‍💫
@lhpl
@lhpl 15 күн бұрын
Dumb professor.
@tylerhummel236
@tylerhummel236 3 ай бұрын
Found out about unions when I was making my final project for CS50x a few days ago. Used one in one of my structs for my fighting sim program.
@YandiBanyu
@YandiBanyu 5 ай бұрын
I have used unions to serialize floating point number as their byte representation. Just write the float to the float part of the union and then read its byte array part when I need to serialize it. Just need to keep in mind the endianess (but that's mostly non-issue for me since the communicating system is always the same MCU)
@grimvian
@grimvian 3 ай бұрын
Thanks for your insightful information about C. Because of my bad hearing I struggle, because of the background music...
@apmcd47
@apmcd47 4 ай бұрын
The X intrinsics toolkit (the one Motif is built on) used this trick but with the type identifier being the first member of each struct in the union.
@Seltyk
@Seltyk 4 ай бұрын
The first time I saw unions being used realistically was in some code for an LED light controller. The union had a struct with one byte per color, a 4-byte RGBI value, and a 4-byte array where each position was one part of RGBI.
@HaydenLikeHey
@HaydenLikeHey 5 ай бұрын
I didn't know that unions operated like this! I've only read about them since I was curious about C's 32 keywords and had never seen this one used. I thought it only contained one type at a time so it's useful to know how they actually work! Thanks for this!
@greenwool4460
@greenwool4460 Ай бұрын
Awesome vid! I remember when my prof was talking about unions I never really got it. I can’t believe it took me this long to actually learn it for real lol
@janAkaliKilo
@janAkaliKilo 5 ай бұрын
Thank you for your videos. I'm not particularly interested in C language. But I write programs in Nim, and it compiles to C. Your insights are very helpful to understand Nim's internals.
@herberttlbd
@herberttlbd 4 ай бұрын
Prior to database management systems, data was written in records composed of fixed-length fields. Unions were used to reinterpret the layout of those records, where the type was indicated at the start of the record to simulate a tagged union similar to your last example, and to provide ways to access elements within a field, e.g. 8 chars for the whole date unioned with 2/2/4 chars for month/day/year. Storing data like this is why the strn* functions exist in the standard library; they weren't intended to be "safe" versions of the non 'n' variants as people started suggesting in the 90s. I don't know if it is useful to learn how computing was done prior to the 80s as a lot of it isn't relevant today unless you find yourself interacting with COBOL but it is helpful if you want to know where some of this stuff comes from.
@thelaagernation9532
@thelaagernation9532 5 ай бұрын
At one time i decided to design an esolang with the idea of it centering around a datatype whos inner type was dynamic. I was originally using a void pointer and doing the casting as required, but unions seem a lot better for that, nice to know
@martinhardy7659
@martinhardy7659 5 ай бұрын
Awesome thanks 👍 I believe these will be useful
@HiHelloHi
@HiHelloHi 5 ай бұрын
I've used something similar to the polymorphism example when sending messages between two processes while working with QNX for an RTOS course
@Colaholiker
@Colaholiker 5 ай бұрын
Being an embedded developer, unions are a daily thing for me. However, there is one little thing I'd like to add - when you discuss the size of your json_t and say that the enum takes up only one byte... while that can be accurate, it isn't necessarily so. It depends on the compiler and its settings - I have worked with compilers where an enum always takes up 32 bits, as this is the native word size of the target architecture. In other cases, the minimum number of bytes needed to represent all values in the enum is used.
@paper_cut9457
@paper_cut9457 5 ай бұрын
I knew about unions but try to avoid them due to the fact that they require extra care in thinking how you are phisically organizing memory in your code (think of an array of unions, for example). In my opinion, another hidden gem in C is the "reserve" keyword. Thanks a lot for the video, high quality as usual !
@rz2374
@rz2374 5 ай бұрын
reserve isn't a keyword in c. did you mean register?
@naomicoffman1315
@naomicoffman1315 5 ай бұрын
@@rz2374 The description of a "hidden gem" made me think of restrict.
@polarpenguin3
@polarpenguin3 5 ай бұрын
​@@rz2374Hopefully not because register is mostly deprecated and the compiler will usually ignore it.
@hallrules
@hallrules 5 ай бұрын
@@rz2374 he probably meant restrict
@itellyouforfree7238
@itellyouforfree7238 5 ай бұрын
I think you mean "restrict", not "reserve"
@alexaneals8194
@alexaneals8194 5 ай бұрын
The only time that I have used unions was to overlay registers. So, I could access EAX or AX depending on whether I needed the 16 bit or 32 bit register, but that was a long time ago and it was only for a hobby project.
@franciscoflamenco
@franciscoflamenco 5 ай бұрын
I used unions a lot in my previous job. The system's learning data would be flashed into ram all at once, and then we'd break it down into smaller and smaller structs depending on the "module" within the system. Because of legacy code, some of the structs could have slightly different type definitions across the code base. Using unions is a slightly more structured way of accessing that memory, as opposed to casting void pointers into the type that you're expecting.
@gaeel330
@gaeel330 9 күн бұрын
I've often used unions like in your last example. Usually I'd ensure correctness by using functions or macros to set both the discriminant and the value, just like your printJSON function ensures that you're correctly interpreting the data. I'd never seen unions used to provide multiple ways to read/write the same underlying data though, like with your IP address and hardware register examples, that's really neat! It makes unions an effective way to avoid the "primitive obsession" antipattern, beyond a simple "typedef int ipv4_addr".
@johningram420
@johningram420 5 ай бұрын
I've used unions to make my C++ code more readable. I had a Vector3 class that I would use to represent rgb color values, and xyz coordinates. Instead of having two Vector3 types, or storing values twice, I used unions for each of the floats.
@moisascholar
@moisascholar 4 ай бұрын
This right here. Great in graphics/game programming when trying to cannibalize memory (especially to have structs/data fit on a single cache line (64-bytes, generally)).
@dliamk
@dliamk 3 ай бұрын
Do you happen to have a git repo I could check out?
@Anubis1101
@Anubis1101 5 ай бұрын
i use unions to break down types like floats and doubles for complex conversion, as well as dynamically access arrays and heaped memory. i think its great practice for any budding programmer to learn to use them, so its sad to hear theyre relatively obscure. theyre super useful even in C++ (even though much of their implementation is UB), much faster than a lot of other included functions and features.
@JoshuaMaciel
@JoshuaMaciel 5 ай бұрын
This was great timing after just learning about Unions in Zig while doing Ziglings last night
@crazychicken0378
@crazychicken0378 5 ай бұрын
Something I love to do with unions is treating a multidimensional array as a single linear array for quick one off tasks that would only require a simple for loop instead of a set of nested for loops. Makes rereading my code easier and thinking a lot easier too
@Songfugel
@Songfugel 5 ай бұрын
Depending on the use case, this might come with a massive performance hit since it bypasses some cpu and cache optimizations available for dealing with 2D data
@user-sl6gn1ss8p
@user-sl6gn1ss8p 5 ай бұрын
@@Songfugel do you mean there are optimizations for, say, double[][], vs a double[] with the same number of elements? Can you give me any pointers on that?
@Songfugel
@Songfugel 5 ай бұрын
@@user-sl6gn1ss8p Yes, you can search for cpu matrix (that is what 2d arrays can be) optimizations and also how keeping the for loops nested to limit the individual task of the work in the last loop to be in cache limits, the speed and cache optimization of the operations can be much better Nested for loops done correctly (you don't branch, and jump out whenever the job is done for that loop) are not bad is some context like 2D number crunching. There is an amazing video about it by DepthBuffer on YT called something like "nested loops can make your code faster" However, not to mislead, I have to point out that nested branches (like nested IF statements) can be very very bad
@kiranchowdary8100
@kiranchowdary8100 5 ай бұрын
nice examples on unions, thanks for video . informative . from India
@dutchcanuck7550
@dutchcanuck7550 5 ай бұрын
Other computing languages have used union-type structures and syntax for decades. For example, COBOL has the REDEFINES clause which does exactly the same thing. It is possible that this feature was added to C in part to enable a C program to interact with software and data from other computer languages. 30 years ago, I was involved in an EDI project (Electronic Data Interchange) involving the receipt of purchase orders and the sending of invoices via X.500. One computer was an IBM mainframe, the other was a Unix minicomputer. X.500 was an expensive protocol, so EDI was designed to send the required data in the smallest packets possible, and made heavy use of REDEFINES and unions to accomplish this.
@johnnybravo9701
@johnnybravo9701 5 ай бұрын
Keep making videos for C they are the best!!!
@darkobakula5190
@darkobakula5190 5 ай бұрын
I consider union an early precursor to polymorphism with capability of adding simple RTTI concept by wrapping union and enum together into a struct, many people use unions this way. It's also the easiest and fastest way to understand polymorphism and it's benefits.
@vishwanathbondugula4593
@vishwanathbondugula4593 5 ай бұрын
I always thought who would use a union, but this video opened my eyes wide open with their power.
@dtikvxcdgjbv7975
@dtikvxcdgjbv7975 2 ай бұрын
Man, Your work is nice. It should enter into Library of Congress.
@GlennHamblin
@GlennHamblin 5 ай бұрын
I find unions very handy for all of the use cases you mentioned and more. As far as goto I generally abhor them, but in certain instances they are just the cockford Ollie and the code is just more logical than writing spaghetti to get around using one. At the end of the day your code should be as simple as possible and no simpler!
@leonid998
@leonid998 Ай бұрын
Please make one about type punning and Undefined behavior (in C and C++) :))
@LordHog
@LordHog 5 ай бұрын
Unions are used in quite a few places. One place it is very useful is in messaging. There is a common messaging API which is used by all cores and task. The messaging size is fixed and is a messaging payload. Each of the task will have a different representation of that data payload. So the overall structure/union is what is accepted by the messaging API, but up to the task what that data represents
@jp46614
@jp46614 4 ай бұрын
Flexibility of unions in C++ however is severely reduced because of stricter safety checks so you have to usually work with some ugly reinterpret cast syntax to make it work
@MotorBorg
@MotorBorg 5 ай бұрын
No experience in c, but I've used a similar feature of Pascal called variant records (if I remember correctly) to access individual words or bytes of an integer.
@hansdampf2284
@hansdampf2284 5 ай бұрын
I think unions are cool for those conversion things where you don’t really convert but just want to have a different view of the data. They are also useful sometimes when you have memory that you can only write in blocks of a fixed size. For example I have NVRAM that can only by written in 32 Bit blocks. I define a Union that consists of a uint32 and a struct that is smaller than that and can save and load my struct onto NVRAM easily. However they can throw people off easily. So I rather use then sparsely. An example of their usage is the network address structs in the conversion between these structs in the C library
@gmodrules123456789
@gmodrules123456789 5 ай бұрын
You should do a video on bitfield structs, with variable width fields. Section 6.9, page 149 in K&R.
@iankeck3419
@iankeck3419 5 ай бұрын
In the example at 3:46, one can define as many fields as the register contains by using bit fields in the structure. While more readable than bit-wise operations, you need to measure to see which is more performant.
@rafa_br34
@rafa_br34 5 ай бұрын
One way I used unions a while ago was to interpret 32-bit color both as an uint8 array and 4 named 8-bit uints using: union RGBA32 { uint8 RGBA[4]; struct { uint8 R, G, B, A; }; };
@bluesillybeard
@bluesillybeard 5 ай бұрын
I use discriminated unions somewhat frequently - although I use Zig, which has nice syntax to make sure that you don't get the field of the wrong type. (similar to Rust enums) Using a regular union to change types is generally a bad idea if you are trying to support multiple platforms, because the way that they organize memory might be slightly different leading to different behavior.
@johnshaw6702
@johnshaw6702 5 ай бұрын
A very good explaination of unions with nice examples. I do wish to point out that, unless you pack a structure, the size will surprise a few people. Structures, arrays, and types are usualy aligned to word (register size) boundries, which are implementation dependent. I once found a bug that wasn't, because the array, containing a string, was automatically aligned. The character array was declared to be 10 and contained 10 characters. The issues was that it reprented a string, which is suppose to be null terminated. The complier actually aligned the array to 12 bytes, not 10, so it worked because the last 2 bytes were 0. Modifying it to be UNICODE compatible made it blow up, because 10 UNICODE characters were aligned and there was no extra bytes to hide the mistake.
@re.liable
@re.liable 5 ай бұрын
I remember using this in Arduino. I wanted to give individual names to my digital output pins, but also iterate through all the pins in a single loop.
@rohansimon7410
@rohansimon7410 5 ай бұрын
Dude, I'm taking a MicroP class right now and Unions are EVERYWHERE. Pretty much all configuration registers for devices are stored in some sort of union.
@Ma_X64
@Ma_X64 5 ай бұрын
I'm always using them programming for MCUs. Sometimes I need some tricky data rearranges and unions helps me.
@souper775
@souper775 3 ай бұрын
Randomly learned about unions through Unreal Engine years back. Vectors are defined structs with a union over the member types.
@dekutree64
@dekutree64 5 ай бұрын
I use them to create a bunch of aliases for the members of vector and matrix types. union{struct{float x,y,z;}; float v[3];} Vector3; union{float m[9]; Vector3 row[3];} Matrix33; union{float m[12]; Vector3 row[4]; struct{Matrix33 mtx33; Vector3 translation;};} Matrix43; Very nice when you need to pass a portion of a composed struct as an argument to a function, or access elements with a loop iterator instead of by individual names. The only drawback is that it clutters the debug watch window.
@dplastico
@dplastico 3 ай бұрын
Where do you get your t-shirts? I love them
@ReconissanceMa
@ReconissanceMa 5 ай бұрын
Yeah you can use a union to do some pretty cool stuff. One is quickly read out the binary data of floats union u{ float f; unsigned int ui; }; union u val; val.f=1.0f; printf("%x",val.ui); output: 3f800000
@Julian-mc3tc
@Julian-mc3tc 5 ай бұрын
I worked on a machine code excutor for a school project. Union saved my butt for "converting" an unsigned short into a array of unisgned char
@Aduskett
@Aduskett 5 ай бұрын
You should do a video on MISRA. It's still widely used in many industries! Also, Unions aren't allowed in MISRA. Great video!
@LowLevelLearning
@LowLevelLearning 5 ай бұрын
Thanks! Will do!
@Aduskett
@Aduskett 5 ай бұрын
@@LowLevelLearning I'm looking forward to watching it! There are all sorts of gotchas in MISRA that I deal with on a day-to-day basis. Such as: - Dealing with pre-processor macros. - Only allowing one exit point of a method. - No Unions - Only one goto or break in a method And many more!
@NeuwDk
@NeuwDk 5 ай бұрын
Unions taught me about endianness, as I was doing something similar to the ipv4addr example and got very confused about the byte order
@ducgia1493
@ducgia1493 3 ай бұрын
It helps to deal with type diversity as well
@jeffcauhape6880
@jeffcauhape6880 5 ай бұрын
Huh.... food for thought. I've never used unions, but I can see how they can be extremely useful in some circumstances. Without unions I would approach those problems with bit-wise manipulations. By the way, excellent presentation.
@EvilP3arProductions
@EvilP3arProductions 5 ай бұрын
They're incredibly useful in game programming since they're the basis of variant data types. Love me a delicious union
@kipchickensout
@kipchickensout 3 ай бұрын
I remember in CS:GO's code that I've seen unions be used for example when representing the coordinates of a Voxel in spatial partitioning as well as its ID (hash?) which was for example used to get all entities inside a specific area on the map or something union Voxel_t { struct { unsigned int x:11; unsigned int y:11; unsigned int z:10; } bitsVoxel; unsigned int uiVoxel; };
@niamotullah99
@niamotullah99 5 ай бұрын
i'm interested in Cyber Security. Know little of C and started to learn Assembly. I like your low level explanation of things. interested to learn more.. Sorry can't afford your course. But your effort deserve something
@OLIV3R_YT
@OLIV3R_YT 5 ай бұрын
Damn, that's cool, thanks ❤
@glitchy_weasel
@glitchy_weasel 5 ай бұрын
Very useful! How about a video about C bitfields next?
@ByronWatts
@ByronWatts 5 ай бұрын
Used it in C and Modula-2 which I also used in production on one project.
@justapasserby6063
@justapasserby6063 5 ай бұрын
On an unrelated matter, I haven't used floats since the olden days of programming on a PDP 11/40 when memory and disk space was at a premium.
@tuckercarlsonbot
@tuckercarlsonbot Ай бұрын
If I can get a desktop support job or something ill get a subscription to ur class for sure.
@MMarcuzzo
@MMarcuzzo 4 ай бұрын
Ive known unions as features. But never how to use them. The one for embedding is simply genius and make everything easier. Also, for network packages/frames is amazing too
@ProfRoxas
@ProfRoxas 5 ай бұрын
I haven't used C in a while but union is probably my favourite feature. But i'm not sure anymore, but i think "the sum of the size of these elements" might slightly be incorrect because of padding? Maybe it was the alignment where different size of the members can cause performance benefits because of how they are in the memory? In the example it fits well, but maybe if the first element was smaller than the second, the sizeof would be bigger because of the padding?
@himonkoch3416
@himonkoch3416 5 ай бұрын
As an embedded developer, unions are SOOO OP it's crazt.
@liam1253
@liam1253 5 ай бұрын
I have used unions in the past for MIDI data to be able to efficiently break apart each byte in the message
@arvind6007
@arvind6007 5 ай бұрын
Literally good feature in C after i see ur polymorphism example, thanks for the vid man
@372leonard
@372leonard 4 ай бұрын
there are 2 use cases where i wish i had unions in C#. 1 with vectors and colors xyzw = rgba 2 with character hitboxes where the position of the hitbox is shared with the characters position. so character.pos = character.hitbox.pos
@soniablanche5672
@soniablanche5672 5 ай бұрын
This reminds me of TypedArray in javascript. You are essentially interpreting a buffer in different ways.
@sempersolus5511
@sempersolus5511 5 ай бұрын
This concept looks very useful for accessing the same memory under different names, types, and formats. I can see why it's contentious; there's a large risk of losing track of what's assigned to the union and making a mistake. But... that's why we have high-level programming. If you're going to program in C, you're going to keep track of memory anyway. Might as well save space while doing it.
@EarlHutchingson
@EarlHutchingson Күн бұрын
The problem with unions is that the C compiler doesn't guarantee most of the use cases you've described If fields are reordered or endianess differs, data conversion will break. It's dangerous to assume otherwise unless you are locked in to a specific system and compiler version. If you write to a union using one type of data and read using another that's "undefined behaviour "
@shriokei
@shriokei 4 ай бұрын
I can see myself using this, I forgot that the union exists, then again I don't use C daily. Great video
Bit Fields in C. What are they, and how do I use them?
13:26
Jacob Sorber
Рет қаралды 77 М.
JavaScript: addEventListener AND forEach method
7:10
Faizan Mohiuddin
Рет қаралды 46
Зомби Апокалипсис  часть 1 🤯#shorts
00:29
INNA SERG
Рет қаралды 6 МЛН
every good programmer should know how to code this data structure (its easy)
21:08
you will never ask about pointers again after watching this video
8:03
Low Level Learning
Рет қаралды 2 МЛН
researchers hack the PS4 with a 20 year old bug
12:21
Low Level Learning
Рет қаралды 21 М.
demystifying the secret structure you've been using all along
8:03
Low Level Learning
Рет қаралды 89 М.
Relative Ranks - Solve with Sam in Python
8:10
Sam Does Leetcode
Рет қаралды 74
i changed my mind about zig
9:34
Low Level Learning
Рет қаралды 143 М.
why is it illegal to use "goto"?
5:23
Low Level Learning
Рет қаралды 218 М.
why do hackers love strings?
5:42
Low Level Learning
Рет қаралды 386 М.
researchers find unfixable bug in apple computers
8:32
Low Level Learning
Рет қаралды 680 М.
i wrote my own memory allocator in C to prove a point
5:23
Low Level Learning
Рет қаралды 325 М.
Samsung or iPhone
0:19
rishton vines😇
Рет қаралды 6 МЛН
Распаковка айфона в воде😱 #shorts
0:25
Mevaza
Рет қаралды 1,4 МЛН
Any Sound & Call Recording Option Amazing Keypad Mobile 📱
0:48
Tech Official
Рет қаралды 325 М.
How Neuralink Works 🧠
0:28
Zack D. Films
Рет қаралды 28 МЛН
Я Создал Новый Айфон!
0:59
FLV
Рет қаралды 3,2 МЛН
Что еще за обходная зарядка?
0:30
Не шарю!
Рет қаралды 2,1 МЛН