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

preview_player
Показать описание
---

When do I use a union in C or C++, instead of a struct? // Unions are useful, but often overlooked in beginner classes, because we don't use them all that much, and because we can often get by without them. This video talks about unions, how they differ from structs, and when you might want to use a union in your C or C++ programs.



***

Welcome! I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.

About me: I'm a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.

More about me and what I do:

To Support the Channel:
+ like, subscribe, spread the word

Рекомендации по теме
Комментарии
Автор

Unions are a case where I believe the verbosity of typing "union foo" (vs hiding behind a typedef) is a feature, not a bug.
When you use a union, you are deliberately making the decision to refer to one memory location by multiple names. That's unusual enough that I want the "union" keyword front and center to draw a reader's attention.

CraverYT
Автор

I used unions in a Sega Master System emulator I'd started working on: the Zilog Z80 microprocessor has 8-bit registers that can pair up and act as though they were 16-bit ones. With the help of unions and structs, I could manipulate such registers both ways without the need for bitwise operations and further logic. Quite useful and clever 😁😁

lean.drocalil
Автор

I love how whenever I stumble across a question about C/C++ essentials, you're posting a video about that exact thing.

DrSTAHP
Автор

Unions are awesome when you're making a programming language with dynamically typed variables. It's nice to have a struct with the value type information and an union storing the actual value.

Reiqy
Автор

a neat thing about unions is you can use them to serialize a float to send it down some serial communication like uart, a float element and an uin32_t element and thats it. then send the uint32_t byte by byte and assemble on the other end back to a float, via pointer or another of the same union. serializaton like this is also useful with structs to send them along their serial way, you don't need a union to do that but it's a much cleaner way than with pointers

EdwinFairchild
Автор

Thanks for this. One of the C books from back in the day (©1988) concluded a very short chapter introducing unions with the unhelpful statement: "The author hasn't yet found a reason for using union structures [sic] instead of solving the problem with other C data types."

matthewkott
Автор

I have been using Linux for over 15 years and struggling to learn C on my own by reading manpages and trying to decipher source code. I have learned more in a few hours on your channel than all those years combined. Thank you for what you do.

xaNull
Автор

In Soviet Russia we share the memory comrade no structs or classes allowed

nonetrix
Автор

Unions seem like one of those things that aren't generally useful, and very error prone, but would have some very good niche cases. Could be useful for something like fast inverse square root, or some case where type punning is useful. Coming from C++, polymorphism would be a lot less error prone I would think for the use case shown here though.

xeridea
Автор

I usually use a union for a UART receive buffer . Then you can use the data type as a uint8_t or a “char” which also uses 8 bits .

RajeshKulkarni
Автор

I absolutely love how you explain all the concepts with a little hands-on video of their implementations.

abxxyz
Автор

I have been waiting for this video. Thanks for talking about unions.
You are my top source of C lessons. Thank you for your efforts.

martandrmc
Автор

Thanks. Explained it well enough for me. Going over structs in a course right now, and the instructor just flat-out says "don't use unions. They are dangerous." What you gave is a perfect use case of when I should consider them.

As with all things low-level programming, they are only dangerous in the hands of a rookie, but powerful in the hands of someone who knows what they are doing. Much appreciated.

LorenHelgeson
Автор

Bold of you to discuss unions without mentioning hardware peripherals where the same configuration space will have different register meanings depending on the version or mode of the peripheral being configured. That's like 95% of the usage for unions.

gregoryfenn
Автор

Very useful with matrices and vectors. Have a union with an anonymous struct inside holding the individual elements, and an array with the size of the number of elements in the top level union. Then you can change/get the values of the elements by their names (like x, y, z etc) or iterate over them using the array.

Psykorr
Автор

I've been programming C++ for like 3 years now and this is the clearest way someone has explained this. Most people just handwave the question and just say it's "some old thing from C, don't worry about it."

coolbrotherf
Автор

This channel is a literal goldmine for someone learning C and C++. Thank you so much!!

TheLonelyLPer
Автор

I searched for ages to find a tutorial to know how to use it, and when i saw this ... i was in paradice

skan
Автор

C unions are very powerful, they basically allow you to implement pattern matching and inheritance without advanced language constructs

marusdod
Автор

Union is very useful for networking, because sometimes we expect structured data (struct) but has to be bytes before being sent. Thus, it would be struct in an union.

KangJangkrik
join shbcf.ru