union Unions with shared storage

union Unions with shared storage

union members share one address. Writes change the active member; other reads are restricted. Size fits the largest member plus possible tail padding.

CategoryStruct / Union / Enum
KindKeyword / Statement
C standardC89 / C90

📝 Syntax

union U { int i; float f; };

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

number = 42
letter = A
shared address = 1
ℹ️ Info The example writes the active member before each use, then compares the union's address with a member's address to demonstrate shared storage without reading an inactive member. sizeof(union Value) may include tail padding and is not guaranteed to equal the largest member's size exactly.

📚 Related Tutorials

❓ FAQ

QIs a union's size always equal to its largest member's size?
ANot necessarily. It must be large enough for the largest member and satisfy the union's overall alignment, so trailing padding may make sizeof return a larger value.
QCan an int be written to a union and then read directly as a float?
AThis should not be treated as numeric type conversion. Members share object representation, and reading through another member involves type-punning and representation rules, potentially including trap representations. Use ordinary assignment or an explicit cast for numeric conversion.
QHow can a program know which member a union currently holds?
AA union does not record its active member automatically. A common approach is to store an enumeration tag alongside it in an outer structure, update the tag whenever a member is written, and check it before reading.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏