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

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

Low Level Learning

6 месяцев назад

125,138 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

LiamF
LiamF - 28.11.2023 13:30

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.

Ответить
Electronlabs
Electronlabs - 28.11.2023 13:02

You can do polymorphism with even dynamic function overload just like in c++ .. with a vtable. It doesnt have to be union :)

Ответить
Sonia Blanche
Sonia Blanche - 28.11.2023 09:28

This reminds me of TypedArray in javascript. You are essentially interpreting a buffer in different ways.

Ответить
BirdBoy
BirdBoy - 28.11.2023 07:48

You should do a video on bitfield structs, with variable width fields. Section 6.9, page 149 in K&R.

Ответить
George Smart, M1GEO
George Smart, M1GEO - 28.11.2023 04:58

In embedded, unions are super useful for setting individual bits and bitfields within a word.

Ответить
dekutree64
dekutree64 - 28.11.2023 04:53

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.

Ответить
Pollux
Pollux - 28.11.2023 01:04

Thanks for sharing, it's pretty neet.

Ответить
hexnano
hexnano - 27.11.2023 23:51

god tier video, gonna use onions for all my register manipulation and organization now!

Ответить
Jakob Kenda
Jakob Kenda - 27.11.2023 22:40

Even Rust has unions that do exactly the same thing as unions in C. They are, of course, unsafe, unlike enums/discriminated unions.

Ответить
Alex Cat
Alex Cat - 27.11.2023 21:37

Grandpa variants

Ответить
Omar Ibrahim
Omar Ibrahim - 27.11.2023 20:02

I learned unions during the first 4 weeks of learning programming (which I did in C). Is it really niche??

Ответить
LogicEu
LogicEu - 27.11.2023 19:54

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.

Ответить
Benjamin Say
Benjamin Say - 27.11.2023 19:46

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.

Ответить
GmanGavin();
GmanGavin(); - 27.11.2023 19:41

So I learned about unions in C then a couple hours later you make a video on it, small world.

Ответить
HWstar
HWstar - 27.11.2023 19:38

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.

Ответить
wintermute181
wintermute181 - 27.11.2023 19:12

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?

Ответить
Dutch Canuck
Dutch Canuck - 27.11.2023 19:09

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.

Ответить
Glenn Hamblin
Glenn Hamblin - 27.11.2023 18:28

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!

Ответить
Homeopathic Fossil-Fuels
Homeopathic Fossil-Fuels - 27.11.2023 18:07

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.

Ответить
MangoDev
MangoDev - 27.11.2023 16:44

:%s/onion/union

Ответить
The Hemperor
The Hemperor - 27.11.2023 16:17

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.

Ответить
Michael Nolan
Michael Nolan - 27.11.2023 15:55

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)

Ответить
Alex G
Alex G - 27.11.2023 15:36

Unions can be useful when you need to write an interpreter with a variable byte length. I learned this thanks to bisqwit

Ответить
Francisco Flamenco
Francisco Flamenco - 27.11.2023 15:33

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.

Ответить
tev olsen
tev olsen - 27.11.2023 14:19

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.

Ответить
Menko
Menko - 27.11.2023 14:16

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

Ответить
Ian Grant
Ian Grant - 27.11.2023 13:58

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! 🙂

Ответить
AlFas
AlFas - 27.11.2023 13:34

C onions are really underrated, now there is a reason to make me cry while using this language

Ответить
Alberto T.
Alberto T. - 27.11.2023 12:53

I know them since I started using C because I used SDL, which use unions for its event types.

Ответить
kumar kumar
kumar kumar - 27.11.2023 11:28

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.

Ответить
Hax Pro
Hax Pro - 27.11.2023 11:28

I've seen unions used in shader code but that the only time I've seen it used.

Ответить
akkudakkupl
akkudakkupl - 27.11.2023 10:31

Heard of it, use it.

Ответить
TheMannyzaur
TheMannyzaur - 27.11.2023 09:54

I've known about unions for a while but never found a situation to actually use them
This video should be interesting

Ответить
Бахтияр Брекешев
Бахтияр Брекешев - 27.11.2023 09:34

I used unions when writing library for stepper motor driver tmc2209
Using structure inside of union nice trick helps a lot

Ответить
idiom axiom
idiom axiom - 27.11.2023 09:16

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.

Ответить
glitchy_weasel
glitchy_weasel - 27.11.2023 08:59

Very useful! How about a video about C bitfields next?

Ответить
Braneloc
Braneloc - 27.11.2023 08:42

Bitfields.
Hex/Binary/Denary conversions

Ответить
Yash
Yash - 27.11.2023 08:42

lets agree that "you've probably never heard of" part in the title dont apply to most of us :)

Ответить
John Shaw
John Shaw - 27.11.2023 08:41

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.

Ответить
Suman Khanra
Suman Khanra - 27.11.2023 08:41

probably the worst video of this channel very poor explanation

Ответить
Amirhossein Alesheikh
Amirhossein Alesheikh - 27.11.2023 08:39

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?

Ответить
Alex Joaquim Pereira
Alex Joaquim Pereira - 27.11.2023 08:30

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.

Ответить
Alex A'Neals
Alex A'Neals - 27.11.2023 07:14

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.

Ответить
The Laager Nation
The Laager Nation - 27.11.2023 07:12

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

Ответить
Ortho Non
Ortho Non - 27.11.2023 06:58

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

Ответить