Комментарии:
If you want to review an obscure, seldom-used feature, you should choose bit fields. Funny thing is, both tend to be used most when working with binary protocols.
ОтветитьYou can do polymorphism with even dynamic function overload just like in c++ .. with a vtable. It doesnt have to be union :)
ОтветитьThis reminds me of TypedArray in javascript. You are essentially interpreting a buffer in different ways.
ОтветитьYou should do a video on bitfield structs, with variable width fields. Section 6.9, page 149 in K&R.
ОтветитьIn embedded, unions are super useful for setting individual bits and bitfields within a word.
Ответить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.
Thanks for sharing, it's pretty neet.
Ответитьgod tier video, gonna use onions for all my register manipulation and organization now!
ОтветитьEven Rust has unions that do exactly the same thing as unions in C. They are, of course, unsafe, unlike enums/discriminated unions.
ОтветитьGrandpa variants
ОтветитьI learned unions during the first 4 weeks of learning programming (which I did in C). Is it really niche??
Ответить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.
ОтветитьI do a good amount of embedded C programming and I’ve never thought of defining masks for registers like that. Very cool! Will try.
ОтветитьSo I learned about unions in C then a couple hours later you make a video on it, small world.
Ответитьwhat you did first with the union having 4 chars and 1 int and was reading values in the desired format is actually UB. This is called type punning. Same thing for the second example.
ОтветитьI’m so confused, I use discriminated unions all the time how is this niche? How else can you do things like have an array of mixed data types or a variety of return values?
Ответить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.
Ответить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!
Ответить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.
Ответить:%s/onion/union
ОтветитьThe last example is exactly how SDL (Simple Direct Media Layer) is using Unions for their Event Queue. It's a structure with a type member and a union of different sub structures.
For anyone curious search for SDL_Event.
I used it for my failed vm (I used it for the object types: dictionary, array, closure, externalfunction, double, char, bool, string, bytearray) (I had memory leak)
ОтветитьUnions can be useful when you need to write an interpreter with a variable byte length. I learned this thanks to bisqwit
Ответить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.
Endianness can be a problem when working with unions.
I've had enough troubles with it that i now prefer a byte array with getters and setters of both endianness when working with multi byte values.
x86 and most ARMs are little endian, but PowerPC and many network protocols are big endian.
It's funny unions are second nature to me. As soon as someone showed me a Colour union where you can extract the R, G, B, A values (this is often used in games) it clicked in my head and I've been missing this feature in other languages. At least TypeScript has enums
ОтветитьThe "never heard of" part of the title is hard to understand! This is amazingly hard to do in a functional programming language. I spent many days trying to find an elegant way to do it in Polymophically-typed Standard ML and I almost figured out how! 🙂
ОтветитьC onions are really underrated, now there is a reason to make me cry while using this language
ОтветитьI know them since I started using C because I used SDL, which use unions for its event types.
ОтветитьHi, I want to learn assembly so where shall i start.. some are suggesting go with the x86 and some are saying go with ARM. which one will be best. thx in advance.
ОтветитьI've seen unions used in shader code but that the only time I've seen it used.
ОтветитьHeard of it, use it.
ОтветитьI've known about unions for a while but never found a situation to actually use them
This video should be interesting
I used unions when writing library for stepper motor driver tmc2209
Using structure inside of union nice trick helps a lot
Not half as cursed as NaN Boxing. Pack 48 bits into a float 64 with 4 bits spare to set the type, and occasionally use the whole thing as a float, but everything is 64 neat and tidy with tagging.
ОтветитьVery useful! How about a video about C bitfields next?
ОтветитьBitfields.
Hex/Binary/Denary conversions
lets agree that "you've probably never heard of" part in the title dont apply to most of us :)
Ответить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.
probably the worst video of this channel very poor explanation
ОтветитьSo what is their difference with rust's enums? I'm wondering if there is a huge difference, considering that we absolutely love them over here and use it basically everywhere, i absolutely count it as one of the biggest selling points of Rust, but then it is not just an obscure thing in C, but also it is counted by some to be an anti pattern at the same tier as goto?
Ответить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.
Ответить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.
Ответить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
ОтветитьThere's a lot of unions in the linux kernel code, and that's how you know unions(or basically any c features used in kernel) are useful
Ответить