Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals

C Data Types

  • C Input Output (I/O)
  • C Programming Operators

C Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

C structs and Pointers

  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Find the Size of int, float, double and char

List of all Keywords in C Language

  • Demonstrate the Working of Keyword long

A union is a user-defined type similar to structs in C except for one key difference.

Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time .

  • How to define a union?

We use the union keyword to define unions. Here's an example:

The above code defines a derived type union car .

  • Create union variables

When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables.

Here's how we create union variables.

Another way of creating union variables is:

In both cases, union variables car1 , car2 , and a union pointer car3 of union car type are created.

Access members of a union

We use the . operator to access members of a union. And to access pointer variables, we use the -> operator.

In the above example,

  • To access price for car1 , car1.price is used.
  • To access price using car3 , either (*car3).price or car3->price can be used.

Difference between unions and structures

Let's take an example to demonstrate the difference between unions and structures:

Why this difference in the size of union and structure variables?

Here, the size of sJob is 40 bytes because

  • the size of name[32] is 32 bytes
  • the size of salary is 4 bytes
  • the size of workerNo is 4 bytes

However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the above example, the size of its largest element, ( name[32] ), is 32 bytes.

With a union, all members share the same memory .

Example: Accessing Union Members

To learn where unions are used, visit Why do we need C Unions?

Table of Contents

  • C unions (Introduction)
  • Access union members
  • Unions vs Structures
  • Only one union member can be accessed at a time

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Next: Packing With Unions , Previous: Structure Assignment , Up: Structures   [ Contents ][ Index ]

15.14 Unions

A union type defines alternative ways of looking at the same piece of memory. Each alternative view is defined with a data type, and identified by a name. A union definition looks like this:

Each alternative declaration looks like a structure field declaration, except that it can’t be a bit field. For instance,

lets you store either an integer (type long int ) or a floating point number (type double ) in the same place in memory. The length and alignment of the union type are the maximum of all the alternatives—they do not have to be the same. In this union example, double probably takes more space than long int , but that doesn’t cause a problem in programs that use the union in the normal way.

The members don’t have to be different in data type. Sometimes each member pertains to a way the data will be used. For instance,

This union holds one of several kinds of data; most kinds are floating points, but the value can also be a code for a continent which is an integer. You could use one member of type double to access all the values which have that type, but the different member names will make the program clearer.

The alignment of a union type is the maximum of the alignments of the alternatives. The size of the union type is the maximum of the sizes of the alternatives, rounded up to a multiple of the alignment (because every type’s size must be a multiple of its alignment).

All the union alternatives start at the address of the union itself. If an alternative is shorter than the union as a whole, it occupies the first part of the union’s storage, leaving the last part unused for that alternative .

Warning: if the code stores data using one union alternative and accesses it with another, the results depend on the kind of computer in use. Only wizards should try to do this. However, when you need to do this, a union is a clean way to do it.

Assignment works on any union type by copying the entire value.

CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Unions in C

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purpose.

All the members of a union share the same memory location. Therefore, if we need to use the same memory location for two or more members, then union is the best data type for that. The largest union member defines the size of the union.

Defining a Union

Union variables are created in same manner as structure variables. The keyword union is used to define unions in C language.

Here is the syntax to define a union in C language −

The "union tag" is optional and each member definition is a normal variable definition, such as "int i;" or "float f;" or any other valid variable definition.

At the end of the union's definition, before the final semicolon, you can specify one or more union variables.

Accessing the Union Members

To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type.

Here is the syntax to access the members of a union in C language −

Initialization of Union Members

You can initialize the members of the union by assigning the value to them using the assignment (=) operator.

Here is the syntax to initialize members of union −

The following code statement shows to initialization of the member "i" of union "data" −

Examples of Union

The following example shows how to use unions in a program −

When the above code is compiled and executed, it produces the following result −

Here, we can see that the values of i and f (members of the union) show garbage values because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well.

Now let's look at the same example once again where we will use one variable at a time which is the main purpose of having unions −

Here, the values of all the Union members are getting printed very well because one member is being used at a time.

Size of a Union

The size of a union is the size of its largest member. For example, if a union contains two members of char and int types. In that case, the size of the union will be the size of int because int is the largest member.

You can use the sizeof() operator to get the size of a union.

In the following example, we are printing the size of a union −

When you compile and execute the code, it will produce the following output −

Difference between Structure and Union

Both structures and unions are composite data types in C programming. The most significant difference between a structure and a union is the way they store their data. A structure stores each member in separate memory locations, whereas a union stores all its members in the same memory location.

Here is a definition of union type called myunion −

The definition of a union is similar to the definition of a structure. A definition of "struct type mystruct" with the same elements looks like this −

The main difference between a struct and a union is the size of the variables. The compiler allocates the memory to a struct variable, to be able to store the values for all the elements. In mystruct , there are three elements − an int, a double, and char, requiring 13 bytes (4 + 8 + 1). Hence, sizeof(struct mystruct) returns 13.

On the other hand, for a union type variable, the compiler allocates a chunk of memory of the size enough to accommodate the element of the largest byte size. The myunion type has an int, a double and a char element. Out of the three elements, the size of the double variable is the largest, i.e., 8. Hence, sizeof(union myunion) returns 8.

Another point to take into consideration is that a union variable can hold the value of only one its elements. When you assign value to one element, the other elements are undefined. If you try to use the other elements, it will result in some garbage.

Example 1: Memory Occupied by a Union

In the code below, we define a union type called Data having three members i , f , and str . A variable of type Data can store an integer, a floating point number, or a string of characters. It means a single variable, i.e., the same memory location, can be used to store multiple types of data. You can use any built-in or user-defined data types inside a union, as per your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.

The following example displays the total memory size occupied by the above union −

Example 2: Memory Occupied by a Structure

Now, let's create a structure with the same elements and check how much space it occupies in the memory.

This stucture will occupy 28 bytes (4 + 4 + 20). Run the code and check its output −

C Language Tutorial

union assignment in c

C Operators

C control structure, branch & jump stmt, union in c programming.

A union in the C programming language is a special data type that allows different variables to be stored in the same memory location. It is similar to a structure but only one member can hold a value at a time.

The syntax for declaring a union in the C programming language is as follows:

In this example, we define a union called Number with an integer member of type int and a floating_point member of type float . We can assign values to one member and access it, but when we assign a value to another member, the previously stored value becomes invalid.

Note: Using unions requires careful handling to avoid undefined behavior. Make sure to access the currently active member.

Here's an example of union initialization and assignment in the C programming language:

In this code, we define a union called ExampleUnion that has three members: intValue of type int, floatValue of type float, and stringValue of type character array (char[20]).

In the main() function, we demonstrate union initialization and assignment.

First, we initialize the myUnion variable with an initial value of 42 for the intValue member using designated initializer syntax.

Next, we declare the anotherUnion variable and assign a value of 3.14 to the floatValue member.

Finally, we access the union members using dot notation (.) and print their values using printf().

Key Points about Unions in C

  • Union allows different variables to share the same memory location.
  • Only one member of a union can hold a value at a time.
  • Unions provide a way to store different types of data in a single variable.
  • Accessing an inactive member of a union can lead to undefined behavior.
  • The size of a union is determined by the size of its largest member.
  • Unions are useful when you need to manipulate different types of data using the same memory space.
  • Unions can be used for type punning, which allows interpreting the bits of one member as another member's type.
  • Unions can be combined with structures to create complex data structures that can hold different types of values.
  • Unions can be initialized using member-wise initialization or designated initialization.
  • Unions do not provide built-in type checking, so it's the programmer's responsibility to keep track of the currently active member.
  • Unions can be nested within other unions, allowing for hierarchical data representation.
  • Unions can be used for efficient memory utilization and compact storage of data, especially in low-level programming and embedded systems.

Union Size and Memory Layout

Union size and memory layout are related to how memory is allocated and organized for unions in programming languages.

In programming, a union is a special data structure that allows storing different types of data in the same memory location. It enables you to define a single variable that can hold values of different types but only one type at a time. The memory allocated for a union is based on the size of its largest member.

The size of a union is determined by the size of its largest member, as unions are allocated enough memory to accommodate the largest member. For example, if a union has members of types int, char, and float, and the float type has the largest size among these, the size of the union will be equal to the size of a float.

The memory layout of a union depends on the programming language and compiler being used. In most languages, including C and C++, the memory layout of a union is such that all members share the same memory location, and their values overlap. This means that changing the value of one member will affect the values of other members if they share the same memory space.

It's important to note that accessing a member of a union that was not the most recently assigned value may result in undefined behavior, as there's no type-checking within unions to ensure that the correct member is being accessed. Therefore, unions require careful handling to ensure that the correct member is used at any given time.

Here's a C example to illustrate the size and memory layout of a union:

In this example, the Data union has three members: i of type int , c of type char , and f of type float . The size of the Data union will be equal to the size of the largest member, which is float in this case. The memory layout will allow each member to occupy the same memory space, resulting in overlapping values when one member is assigned after another.

As you can see, when a member is assigned, the value of other members might change, as they share the same memory space. It's crucial to keep track of which member is valid at a given time to avoid unintended behavior.

Unions with Structures in C

In this code, we define two structures: struct Rectangle and struct Circle. These structures represent a rectangle with width and height, and a circle with a radius, respectively.

We then define a union called union Shape, which includes the struct Rectangle and struct Circle as its members.

The printShape() function takes an instance of the union Shape as a parameter and determines the shape type by comparing the size of the union with the sizes of the individual structures. It then prints the details of the corresponding shape.

In the main() function, we create an instance of union Shape called shape and assign values to its members. We first assign values to the rectangle member and then call printShape() to print its details. Next, we assign values to the circle member and call printShape() again to print the circle's details.

Enumerated Union in C Programming

To declare an enumerated union, you use the following syntax:.

The enum keyword is used to define the members of the enumerated union. The type keywords are used to specify the data types of the members. The variable name is used to refer to the enumerated union variable.

The following example declares an enumerated union called Color that has three members: RED, GREEN, and BLUE:

The Color enumerated union can be used to store any of the three colors: red, green, or blue. The member member can be used to store the color as an enumerated constant, while the red, green, and blue members can be used to store the color as an integer value.

The following code shows how to use the Color enumerated union:

The code above will print the following output to the console:

This is because the RED enumerated constant has a value of 1.

Enumerated unions can be a useful data structure for storing data that can be represented by a set of named constants. They can also be used to improve the readability and maintainability of your code.

Here's an example of a program using a structure that includes a union for representing colors:

In this program, we define a structure called Color, which includes a union. The union contains an enumeration member member that represents the color (RED, GREEN, or BLUE), and a struct that represents the RGB values (red, green, and blue).

In the main function, we declare a variable color of type union Color. We assign the member of the union as BLUE and then use a switch statement to print the corresponding color name.

Next, we assign specific values to the red, green, and blue members of the union and print them.

Note that when using the struct members of the union, you access them directly without referencing the union's name.

When compiling and running this program, you should see the output:

This demonstrates how you can use a structure with a union to represent different aspects of a color using a common memory location.

Unions and Bit Fields in C

Unions and bit fields are two special data types in C that can be used to save memory and improve performance.

A union is a data type that can store multiple data values of different types in the same memory location. This is useful when you need to store multiple related values, such as the x, y, and z coordinates of a point.

To declare a union in C, you use the following syntax:

A union can only store one value at a time. When you assign a value to a union member, all other members of the union are set to their default values.

A bit field is a data type that can store a single bit of data. This is useful when you need to store small pieces of data, such as flags or Boolean values.

To declare a bit field in C, you use the following syntax:

The bit_field() macro takes two arguments: the number of bits to store and the name of the bit field.

Bit fields are stored in the same memory location as the other members of the struct. The size of the struct is increased by the number of bits specified for each bit field.

Unions and bit fields can be used to save memory and improve performance. However, they should be used with care. Unions can lead to unexpected behavior if you are not careful, and bit fields can be difficult to read and maintain.

Here are some examples of how unions and bit fields can be used:

  • Storing multiple related values: A union can be used to store multiple related values, such as the x, y, and z coordinates of a point. This can save memory, because only one value needs to be stored in memory at a time.
  • Storing small pieces of data: Bit fields can be used to store small pieces of data, such as flags or Boolean values. This can save memory, because only the bits that are needed are stored.
  • Improving performance: Unions and bit fields can be used to improve performance by reducing the number of memory accesses. For example, if you need to store a large number of flags, you can use a bit field to store each flag in a single bit. This can improve performance, because fewer memory accesses are required to read or write the flags.

Unions and bit fields should not be used when:

  • You need to store large amounts of data.
  • You need to store data that is not related.
  • You need to store data that is not fixed in size.
  • You need to be able to read or write data in a random order.

Bit Fields Example in C

Bit fields allow you to allocate specific numbers of bits within a structure to store data. This feature is useful when you want to optimize memory usage or manipulate individual bits of data. You can specify the number of bits each member should occupy within the structure.

Here's an example of a structure with bit fields:

Type checking and error handling with unions in c.

In the C programming language, unions provide a way to define a type that can hold different types of data, but only one at a time. When using unions, type checking and error handling can be a bit more challenging compared to structures or individual variables because the type of data stored in a union is not explicitly tracked.

Tagged Union (Discriminated Union)

One common approach is to use a tagged union, also known as a discriminated union. This involves adding an additional field to the union, commonly called a tag, that specifies the type of data currently stored. For example:

Convention-based approach

Another approach is to establish a convention for using the union, where you rely on some external mechanism (such as comments or naming conventions) to indicate the type of data stored. This approach is less robust because it relies on developers following the convention correctly and lacks the built-in type checking provided by the tagged union approach.

Error Handling

Error handling with unions can be challenging because accessing the wrong member of a union can lead to undefined behavior. It's important to ensure that you always access the correct member based on the current type.

One way to handle errors is by using assertions or conditionals to verify the current type before accessing a specific member:

You can also consider using enums or error codes to indicate and handle errors related to unions in a more structured way.

Remember that unions in C provide flexibility but also require careful handling to avoid errors. It's important to establish clear conventions or use a tagged union approach to ensure type checking and handle errors appropriately.

  • Learn C Language
  • Learn C++ Language
  • Learn python Lang

How to Use C Structures, Unions and Bit Fields with Examples

Structures, Unions and Bit fields are some of the important aspects of C programming language.

While structures are widely used, unions and bit fields are comparatively less used but that does not undermine their importance.

In this tutorial we will explain the concept of Structures, Unions and Bit fields in C language using examples.

1. Structures in C

Structure provides a way to store multiple variables of similar or different types under one umbrella. This makes information more packaged and program more modular as different variables referring to different values can be accessed through a single structure object.

An example of a C structure can be :

So we see that a structure can be defined through a keyword ‘struct’ followed by structure name. The body of structure consists of different semicolon terminated variable definitions within curly braces.

Going back to what structure really is, A structure usually does not package unrelated variables. All the variables are usually part of some broader level information that structure intends to hold.

For example, a structure can hold all the information related to an employee in an organization:

Now, to access a structure variables, you need to define an object for that structure. For example, here is how you can define an object for the ’employee’ structure :

NOTE : The keyword ‘struct’ is mandatory while defining structure objects in C

The variable ’emp_obj’ now becomes object of ’employee’ structure. Individual structure members can be accessed in the following way :

So we see that ‘.’ is used to access individual variables

Unlike the one above, a structure object can also be of a pointer type. For example :

In this case, individual structure members can be accessed in the following way :

So we see that ‘->’ is used to access individual variables.

Here is a working example of C structure :

Here is the output :

2. Unions in C

Unions are almost like structures in C (just explained above) but with a twist. The twist is that the memory for a union is equal to the size of it’s largest member. Confused? No worries, lets understand it in more detail.

Here is how Unions are defined :

As you can see that it’s more or less like how we declare structures in C. Just that the keyword ‘union’ is used instead of ‘struct’.

So, what is the difference between a structure and a union? Well, the difference lies in the size. If the above example would have been a structure, the size of structure would have been :

sizeof(char) + sizeof(unsigned int)

ie 1 + 4 = 5 bytes.

But, in case of a union, the size is equivalent to that of the largest member type in union. So, in this case, the largest type is ‘unsigned int’ and hence the size of union becomes ‘4’.

Now, having understood that, one might ask, in which scenarios union can be used? Well, there are certain scenarios where you want to use only one of the members at a time. So in that case, using a union is a wise option rather than using a structure. This will save you memory.

Here is a working example of a Union in C :

On a different note, to get more deeper understanding of C language, you should also know how C Macros / Inline Functions and C Binary Tree works.

3. Bit fields in C

There are times when the member variables of a structure represent some flags that store either 0 or 1. Here is an example :

If you observe, though a value of 0 or 1 would be stored in these variables but the memory used would be complete 8 bytes.

To reduce memory consumption when it is known that only some bits would be used for a variable, the concept of bit fields can be used.

Bit fields allow efficient packaging of data in the memory. Here is how bit fields are defined :

The above declaration tells the compiler that only 1 bit each from the two variables would be used. After seeing this, the compiler reduces the memory size of the structure.

Here is an example that illustrates this :

Also, if after declaring the bit field width (1 in case of above example), if you try to access other bits then compiler would not allow you to do the same.

Here is an example :

So, by setting the value to ‘2’, we try to access more than 1 bits. Here is what compiler complains :

So we see that compiler effectively treats the variables size as 1 bit only.

If you enjoyed this article, you might also like..

 

Tagged as: C Bitfield , C Struct Array , C Struct Example , C Struct Initialization , C Struct Tutorial , C Typedef Struct , typedef struct , Union in C

Comments on this entry are closed.

Thanks a lot,

Very useful article..

A useful use of unions is to provide a mechanism to interact with embedded electronics devices which have registers which are controlled by bits in registers, in groups of one or more contiguous bits. I.E. single bit flags to indicate interrupt status, the receipt of a character in a UART, etc, or three or more bits in a contiguous block which may indicate the number of bytes available in a UART receive buffer for example.

In this use case, proper use of unions can make the code easier to understand by code maintainers.

Update: Sorry, I meant bitfields.

You have an error in your article. When you talk about unions vs. structures, you say that an equivalent structure would have the size of sizeof(char)+sizeof(int). This is not true. The size of a structure is not the sum of its elements because of alignment issues. A structure with an unsigned int and a char may have sizeof = 8.

Output to the following code is: 8

thanks. useful refresher…

It would also be good to mention memory consumption of structs. For example: struct char_and_ascii { char ch; unsigned int ascii_val; };

Someone would expect that sizeof( char_and_ascii ) = 5, but most of the time, it will be bigger, because of the padding that is added.

So if you allocate memory for a struct and you write to it, it could be possible that you are already out of bounds, but because of the extra memory allocated for the padding you won’t get a segmentation fault.

Very nice article.

Keep it Up.

Hi, Thanks a lot for this nice article.

how, sizeof(example2) is 4 in the concept of BIT FIELDS IN C ? I didn’t get it.

@karthik: As there are 32 bits in 4 bytes, and only 2 bits of these are used [leaving 30 other bits NOT used], the example2 structure only needs ONE int to handle 32 bits.

The example of using a union is non-standard (although it is a commonly used trick). The standard, however, allows only reading the union through that member which was last assigned. Thus, using obj.ascii_val in printf is forbidden by standard. Also, the code sample would give “[65]” as the obj.ascii_val value ONLY in little-endian architecture. On a Sparc machine, or any other big-endian computer, it would be “[16640]” (decimal equivalent of hex 0x4100). This is one of the reasons why the standard forbids such a use. Needless to say, be it legal or not, such a construct can be a very easy way to detect the endianess programatically.

Nice one, thank you!

Very helpful. Thanks

This articles are really Amazing, they help me to understand everything in a simple way.

Next post: Perl Testing with Test::More use_ok, can_ok, is, isnt, like, unlike Functions

Previous post: How to Change Process Priority using Linux Nice and Renice Examples

Linux 101 Hacks Book

  • Bash 101 Hacks eBook - Take Control of Your Bash Command Line and Shell Scripting
  • Sed and Awk 101 Hacks eBook - Enhance Your UNIX / Linux Life with Sed and Awk
  • Vim 101 Hacks eBook - Practical Examples for Becoming Fast and Productive in Vim Editor
  • Nagios Core 3 eBook - Monitor Everything, Be Proactive, and Sleep Well

POPULAR POSTS

  • 15 Essential Accessories for Your Nikon or Canon DSLR Camera
  • 12 Amazing and Essential Linux Books To Enrich Your Brain and Library
  • 50 UNIX / Linux Sysadmin Tutorials
  • 50 Most Frequently Used UNIX / Linux Commands (With Examples)
  • How To Be Productive and Get Things Done Using GTD
  • 30 Things To Do When you are Bored and have a Computer
  • Linux Directory Structure (File System Structure) Explained with Examples
  • Linux Crontab: 15 Awesome Cron Job Examples
  • Get a Grip on the Grep! – 15 Practical Grep Command Examples
  • Unix LS Command: 15 Practical Examples
  • 15 Examples To Master Linux Command Line History
  • Top 10 Open Source Bug Tracking System
  • Vi and Vim Macro Tutorial: How To Record and Play
  • Mommy, I found it! -- 15 Practical Linux Find Command Examples
  • 15 Awesome Gmail Tips and Tricks
  • 15 Awesome Google Search Tips and Tricks
  • RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
  • Can You Top This? 15 Practical Linux Top Command Examples
  • Top 5 Best System Monitoring Tools
  • Top 5 Best Linux OS Distributions
  • How To Monitor Remote Linux Host using Nagios 3.0
  • Awk Introduction Tutorial – 7 Awk Print Examples
  • How to Backup Linux? 15 rsync Command Examples
  • The Ultimate Wget Download Guide With 15 Awesome Examples
  • Top 5 Best Linux Text Editors
  • Packet Analyzer: 15 TCPDUMP Command Examples
  • The Ultimate Bash Array Tutorial with 15 Examples
  • 3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
  • Unix Sed Tutorial: Advanced Sed Substitution Examples
  • UNIX / Linux: 10 Netstat Command Examples
  • The Ultimate Guide for Creating Strong Passwords
  • 6 Steps to Secure Your Home Wireless Network
  • Turbocharge PuTTY with 12 Powerful Add-Ons
  • Linux Tutorials
  • Sed Scripting
  • Awk Scripting
  • Bash Shell Scripting
  • Nagios Monitoring
  • IPTables Firewall
  • Apache Web Server
  • MySQL Database
  • Perl Programming
  • Google Tutorials
  • Ubuntu Tutorials
  • PostgreSQL DB
  • Hello World Examples
  • C Programming
  • C++ Programming
  • DELL Server Tutorials
  • Oracle Database
  • VMware Tutorials

About The Geek Stuff

Copyright © 2008–2024 Ramesh Natarajan. All rights reserved | Terms of Service

C Programming Tutorial Index

Union is a user-defined data type in C, which stores a collection of different kinds of data, just like a structure. However, with unions, you can only store information in one field at once. This tutorial guides you on how to use Union in C Programming

  • Union is like struct, except it uses less memory.
  • The keyword union  is used to declare the union in C.
  • Variables inside the union are called members of the union .

Defining a Union in C

Accessing union members in c.

Program Output:

cppreference.com

Struct and union initialization.

(C11)
Miscellaneous

When initializing an object of struct or union type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of initializers for the members:

expression (1) (until C99)
designator(optional) expression (2) (since C99)
(3) (since C23)

where the designator is a sequence (whitespace-separated or adjacent) of individual member designators of the form . member and array designators of the form [ index ] .

All members that are not initialized explicitly are empty-initialized .

Explanation Nested initialization Notes Example References See also

[ edit ] Explanation

When initializing a union , the initializer list must have only one member, which initializes the first member of the union unless a designated initializer is used (since C99) .

When initializing a struct , the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99) , and all subsequent initializers without designators (since C99) initialize the struct members declared after the one initialized by the previous expression.

A designator causes the following initializer to initialize the struct member described by the designator. Initialization then continues forward in order of declaration, beginning with the next element declared after the one described by the designator.

{int sec,min,hour,day,mon,year;} z = {.day=31,12,2014,.sec=30,15,17}; // initializes z to {30,15,17,31,12,2014}
(since C99)

It's an error to provide more initializers than members.

[ edit ] Nested initialization

If the members of the struct or union are arrays, structs, or unions, the corresponding initializers in the brace-enclosed list of initializers are any initializers that are valid for those members, except that their braces may be omitted as follows:

If the nested initializer begins with an opening brace, the entire nested initializer up to its closing brace initializes the corresponding member object. Each left opening brace establishes a new current object . The members of the current object are initialized in their natural order , unless designators are used (since C99) : array elements in subscript order, struct members in declaration order, only the first declared member of any union. The subobjects within the current object that are not explicitly initialized by the closing brace are empty-initialized .

If the nested initializer does not begin with an opening brace, only enough initializers from the list are taken to account for the elements or members of the member array, struct or union; any remaining initializers are left to initialize the next struct member:

When designators are nested, the designators for the members follow the designators for the enclosing structs/unions/arrays. Within any nested bracketed initializer list, the outermost designator refers to the and selects the subobject to be initialized within the only.

example ex2 = { // current object is ex2, designators are for members of example .in_u.a8[0]=127, 0, 0, 1, .addr=80}; struct example ex3 = {80, .in_u={ // changes current object to the union ex.in_u 127, .a8[2]=1 // this designator refers to the member of in_u } };

If any subobject is explicitly initialized twice (which may happen when designators are used), the initializer that appears later in the list is the one used (the earlier initializer may not be evaluated):

{int n;} s = { ("a\n"), // this may be printed or skipped .n= ("b\n")}; // always printed

Although any non-initialized subobjects are initialized implicitly, implicit initialization of a subobject never overrides explicit initialization of the same subobject if it appeared earlier in the initializer list (choose clang to observe the correct output):

typedef struct { int k; int l; int a[2]; } T; typedef struct { int i; T t; } S; T x = {.l = 43, .k = 42, .a[1] = 19, .a[0] = 18 }; // x initialized to {42, 43, {18, 19} } int main(void) { S l = { 1, // initializes l.i to 1 .t = x, // initializes l.t to {42, 43, {18, 19} } .t.l = 41, // changes l.t to {42, 41, {18, 19} } .t.a[1] = 17 // changes l.t to {42, 41, {18, 17} } }; ("l.t.k is %d\n", l.t.k); // .t = x sets l.t.k to 42 explicitly // .t.l = 41 would zero out l.t.k implicitly }

Output:

However, when an initializer begins with a left open brace, its is fully re-initialized and any prior explicit initializers for any of its subobjects are ignored:

fred { char s[4]; int n; }; struct fred x[ ] = { { { "abc" }, 1 }, // inits x[0] to { {'a','b','c','\0'}, 1 } [0].s[0] = 'q' // changes x[0] to { {'q','b','c','\0'}, 1 } }; struct fred y[ ] = { { { "abc" }, 1 }, // inits y[0] to { {'a','b','c','\0'}, 1 } [0] = { // current object is now the entire y[0] object .s[0] = 'q' } // replaces y[0] with { {'q','\0','\0','\0'}, 0 } };
(since C99)

[ edit ] Notes

The initializer list may have a trailing comma, which is ignored.

In C, the braced list of initializers cannot be empty (note that C++ allows empty lists, and also note that a in C cannot be empty):

(until C23)

The initializer list can be empty in C as in C++:

(since C23)

Every expression in the initializer list must be a when initializing aggregates of any storage duration.

(until C99)

As with all other , every expression in the initializer list must be a when initializing aggregates of static or thread-local(since C11) :

struct {char* p} s = { (1)}; // error

The of the subexpressions in any initializer is indeterminately sequenced (but not in C++ since C++11):

n = 1; struct {int x,y;} p = {n++, n++}; // unspecified, but well-defined behavior: // n is incremented twice in arbitrary order // p equal {1,2} and {2,1} are both valid
(since C99)

[ edit ] Example

This section is incomplete
Reason: more practical examples, perhaps initialize some socket structs

Possible output:

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.7.9/12-39 Initialization (p: 101-105)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.7.9/12-38 Initialization (p: 140-144)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.7.8/12-38 Initialization (p: 126-130)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 6.5.7 Initialization

[ edit ] See also

for Aggregate initialization
  • Todo with reason
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 26 January 2023, at 04:21.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory separately for each member variable. The size of the union is equal to the size of the largest data type.

Memory space can be used by one member variable at one point in time, which means if we assign value to one member variable, it will automatically deallocate the other member variable stored in the memory which will lead to loss of data.

Need of Union in C++

  • When the available memory is limited, it can be used to achieve memory efficiency.
  • It is used to encapsulate different types of data members.
  • It helps in optimizing the performance of applications.

Syntax of Union in C++

Union is defined using the ‘union’ keyword.

After defining the union we can also create an instance of it the same as we create an object of the class or declare any other data type.

Example of Union in C++

             

We have not assigned the values to all data members in one go as we do normally because they share the same memory location and if we do so then their value will be overwritten.

C++ Program to Illustrate that Data Members of Union Share Same Memory Location

In the below example, we are verifying that is it actually data members of the union are sharing the same memory or not.

           

Explanation

First, we have defined a union and defined three different data members inside it. After that, in the main function, we have defined a union variable. Now, we have printed the address of all data members of the union using the reference operator ‘&’.

We can see in the output that the addresses of all three data members are the same which proves that members of the union shared the same memory. We have also printed the size of a union which is ‘8’ because double takes 8 bytes and it largest among int, float, and double.

Anonymous Unions in C++

Just like anonymous objects we also have anonymous unions in C++ that are declared without any name inside a main function. As we do not define any union variable we can directly access the data members of the union that is why their data members must be declared with unique names to avoid ambiguity in the current scope.

In the main function, we have defined an anonymous without defining any variable. After that, we assigned value to data members of a union and print them.

           

Union-like Classes in C++

A union-like class is just a class with at least one anonymous union defined inside it and the data members defined in an anonymous union are known as variant members .

Example: C++ program to illustrate Union-like classes

                 

In the above example, we have created a class ‘student’ a data member, and an anonymous union inside it which is called a union-like class. After that, we created an object for student class ‘s1’ using which we can access the data member of the student class and anonymous union members. So, using object ‘s1’ we assign values to class data members and union data members and then print their values.

author

Please Login to comment...

Similar reads.

  • Top Android Apps for 2024
  • Top Cell Phone Signal Boosters in 2024
  • Best Travel Apps (Paid & Free) in 2024
  • The Best Smart Home Devices for 2024
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

SEIU Local 521

  • 2022 Local-wide Election
  • SEIU 521 Executive Board
  • Mission & Vision
  • Riko Mendez, Chief Elected Officer
  • Member Caucuses, Councils & Committees
  • Work With Us
  • Become a Member
  • Member Resource Center (MRC)
  • Know Your Rights
  • Steward Training Modules
  • Union Difference Calculator
  • MemberLink – Member Portal
  • Building Political Power for Working Families
  • Member Resources
  • Contract Enforcement
  • Questions & Answers
  • Sign up for text/email updates
  • Form a Union at Your Workplace
  • Why Form a Union
  • Where We Work
  • 2024 Primary Election Hub & Endorsements
  • Sign the Union Authorization Card
  • Trainings / Education / Healthcare
  • Fixing the Rigged Economy
  • Housing Justice
  • Immigrant Justice
  • Retirement Security
  • Bimonthly Newswire
  • Press Releases
  • Media Contacts
  • Video Library
  • 521 In the News

union assignment in c

At SEIU Local 521, our mission is to provide our members with a voice in the workplace, in their union and in the larger community. Through our actions, we intend to create a more just and humane society. We are committed to protecting and improving the lives of workers and their families. We will work to improve and protect the services we provide to our communities. We believe that by working together as a united front, we can win better contracts and build industry power in our region.

Are you represented by SEIU 521 at your workplace? Our strength lies in our unity and our numbers. With more union members, we have more power to win better contracts, and a stronger voice together with our co-workers to protect our rights, healthcare, and retirement benefits.

Don’t have a union at your workplace? People form unions at their workplaces because it gives us the strength in numbers to improve our jobs and our communities. Are you looking to organize a union with your co-workers? Have questions about forming a union? Get started today!

For Our Members ›

As a union member, this statement could save your job:.

union assignment in c

Being a union member has its benefits.

union assignment in c

Contact SEIU 521 Member Resource Center (MRC) for assistance.

union assignment in c

Find out the resources we have for our union members.

Background image of a family

Family Child Care

As Family Child Care Providers, we know that in partnership with the families we serve, we strengthen the physical, cognitive and emotional growth of our children. With that same spirit of unity and commitment, Family Child Care Providers are working together to build and grow our union. We will have a seat at the table to improve the early care and education system, our working conditions and the lives of working families in California.

Cuidado Infantil En Familia

Como proveedoras de cuidado infantil, sabemos que junto a las familias a las que servimos, fortalecemos el desarrollo y crecimiento físico, cognitivo y emocional de nuestros niños. Con ese mismo espíritu de unidad y compromiso, las Proveedoras de Cuidado Infantil en Familia estamos trabajando juntas para formar y crecer nuestra unión. Seremos la voz y el voto para mejorar nuestro sistema de educación temprana, nuestras condiciones de trabajo y las vidas de las familias trabajadoras en California.

Child Care Providers Make History: Women Of Color-led Union Wins Agreement With State To Raise Provider Pay And Increase Access To Child Care For California Families

After months of negotiations, countless calls to the Governor, and demanding our voices be heard across California, we’ve reached a tentative agreement with the state that will finally give all child care providers at least a 15% pay increase starting in…

California State Unit 12

| | | | |

Job Protection Insurance Voting Rights Leadership Credit Union Apprenticeship Opportunities Educational Reimbursement Discounts

Member Benefits

A Union is more than the workers themselves. Workers who join together for a common cause and for common interests have strength, more strength than they can ever achieve individually. California State Bargaining Unit 12 exists to protect and advance individual and collective rights in wages, benefits, hours of work, and working conditions for the benefit of workers, their families, their communities, and the State of California.

The collective dues paid by all the employee members provide the means to have the finest legal, financial, political advocacy, and daily representation needed and required to protect, advance, and preserve the rights attained.

As a member you have the right to participate in and vote on all of the matters that affect you and your family in your work place. It is an important right, we feel it is the most important.

Back to top

Job Protection

Members have the full power of the Union to represent, protect, and defend them in any discipline, grievance, arbitration, or other matter that may occur in the workplace. Non-members do not receive representation in any matter other than grievances. Hiring a private attorney — in the simplest of matters — can cost a minimum of $1,500 to $2,000. In complicated cases, attorney fees can run to $10,000 or more per case.

Membership Life and Accidental Death and Dismemberment Insurance

As a member, you will have an automatic $3,000 Life Insurance plus an additional $3,000 Accidental Death and Dismemberment Insurance Policy at no cost to you. Non-members are not eligible for this benefit.

Only Members Have a Right to Vote

Only members can attend union meetings, vote in Local Union elections, vote on how the Union should be run, vote on what it should be trying to accomplish, or vote on what it shouldn’t be doing. Only members can offer proposals for negotiations for new contracts. Only members can vote on the ratification of any new contract. Only members have a say, a vote on what is happening to you in your workplace, on your salaries, on your working conditions, on your benefits. Non-members don’t have any of these rights.

Union Leadership

As a member, you may qualify for election or appointment as a Steward if you want to become actively engaged in the Unit activities. As a member, you may qualify for appointment on the Unit-wide negotiating team, the unit-wide or departmental safety committees, the Unit-wide or departmental joint management-labor committees, the Unit-wide or departmental Apprenticeship committees, on any committee that is formed or activated. Non-members cannot participate in these activities.

Credit Union

Members are eligible for IUOE Credit Union membership with assets in the hundreds of millions of dollars. Checking, savings, Visa cards, auto, boat, motorcycle, recreational vehicles, motor homes, trailers, mobile home loans, home and personal loans, first mortgages on homes — all at the UNION interest rates, the lowest to be found anywhere.

250 North Canyons Parkway Livermore CA 94551 Telephone: 925-454-4000 FAX: 925-454-4005 Toll Free: 800-877-4444 Web Site: www.oefcu.org

Apprenticeship Opportunities

Members can view appreticeship opportunities at the Division of Apprenticeship Standards (DAS) website. These opportunities give members a chance to gain employable lifetime skills and provides employers with a highly skilled and experienced workforce while strengthening California's economy. Click here to access website.

Educational Reimbursement

Members may be eligible for reimbursement of tuition and books costs for classes taken are for the purpose of improving job skills or for job advancement. Annually, members' children are eligible to apply for college scholarships that are awarded by the Locals. Non-members are not eligible for these benefits.

We teamed up with BenefitHub to provide our valued members access to exclusive discounts not available to the public including, Disneyland, Universal Studios, LEGOLAND, SeaWorld, CityPASS, Hotels, and lots more!

To access the discounts, send your name, employer, job site and job classification to: [email protected] . Once your Unit 12 membership is validated, you will receive an email with the BenefitHub website links.

© IUOE California State Unit 12 1620 North Market Blvd, Sacramento, CA 95834 Telephone: 916-444-6880 — FAX 916-444-6877 email: [email protected] www.unit12.org

  • Election 2024
  • Entertainment
  • Newsletters
  • Photography
  • AP Buyline Personal Finance
  • AP Buyline Shopping
  • Press Releases
  • Israel-Hamas War
  • Russia-Ukraine War
  • Global elections
  • Asia Pacific
  • Latin America
  • Middle East
  • Election results
  • Google trends
  • AP & Elections
  • U.S. Open Tennis
  • Paralympic Games
  • College football
  • Auto Racing
  • Movie reviews
  • Book reviews
  • Financial Markets
  • Business Highlights
  • Financial wellness
  • Artificial Intelligence
  • Social Media

Workers at General Motors joint venture battery plant in Tennessee unionize and will get pay raise

Image

FILE - A General Motors logo is displayed outside the General Motors Detroit-Hamtramck Assembly plant on Jan. 27, 2020, in Hamtramck, Mich. (AP Photo/Paul Sancya, File)

  • Copy Link copied

DETROIT (AP) — About 1,000 workers at a General Motors joint venture electric vehicle battery plant in Spring Hill, Tennessee, will get big pay raises now that they have joined the United Auto Workers union.

GM and LG Energy Solution of Korea, which jointly run the plant, agreed to recognize the union after a majority of workers signed cards saying they wanted to join, the UAW said Wednesday.

Both sides will bargain over local contract provisions, but worker pay and other details will fall under the UAW national contract negotiated last fall, the union said in a prepared statement. Starting pay which was $20 per hour will rise to a minimum of $27.72. Over three years, minimum production worker pay will rise to $30.88, the contract says.

The joint venture, Ultium Cells LLC, said in a release that the union recognition came after an independently certified process that ended Tuesday. “We believe this will support the continuity of operations, drive innovation, and enhance world-class manufacturing,” the release said.

Representation of the battery plant gives the UAW another foothold in U.S. southern states as it tries to organize nonunion auto plants. Workers at a 4,300-employee Volkswagen assembly plant in Chattanooga, Tennessee , voted in April to join the union, and contract bargaining is expected to begin this month.

Image

But the union lost its first organizing vote in May at a Mercedes assembly plant and other facilities near Tuscaloosa, Alabama.

Spring Hill is the second GM joint venture battery plant to join the union and fall under the national contract. Workers at a plant near Warren, Ohio, voted to join the union in 2022.

Battery cell production began in Spring Hill earlier this year.

union assignment in c

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants

C Data Types

  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples
  • Find the Size of int, float, double and char

List of all Keywords in C Language

  • Demonstrate the Working of Keyword long
  • C Dynamic Memory Allocation

A union is a user-defined type similar to structs in C except for one key difference.

Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time .

  • How to define a union?

We use the union keyword to define unions. Here's an example:

The above code defines a derived type union car .

  • Create union variables

When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables.

Here's how we create union variables.

Another way of creating union variables is:

In both cases, union variables car1 , car2 , and a union pointer car3 of union car type are created.

Access members of a union

We use the . operator to access members of a union. And to access pointer variables, we use the -> operator.

In the above example,

  • To access price for car1 , car1.price is used.
  • To access price using car3 , either (*car3).price or car3->price can be used.

Difference between unions and structures

Let's take an example to demonstrate the difference between unions and structures:

Why this difference in the size of union and structure variables?

Here, the size of sJob is 40 bytes because

  • the size of name[32] is 32 bytes
  • the size of salary is 4 bytes
  • the size of workerNo is 4 bytes

However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the above example, the size of its largest element, ( name[32] ), is 32 bytes.

With a union, all members share the same memory .

Example: Accessing Union Members

To learn where unions are used, visit Why do we need C Unions?

Table of Contents

  • C unions (Introduction)
  • Access union members
  • Unions vs Structures
  • Only one union member can be accessed at a time

Sorry about that.

Related Tutorials

C structs and Pointers

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

C alignment in union

In the K&R C programming code, the following code is given

Then it goes on to say that "The Align field is never used; it just forces each header to be aligned on a worst-case boundary". I have read the text multiple times but still do not understand why long is needed for alignment. SIZE is an int and PTR is 4 bytes, so shouldn't it be aligned anyways? And why use long, and not int? Thanks.

George Newton's user avatar

  • Did you realize that the way the code was written in your question was completely wrong? –  Sourav Ghosh Commented Jan 30, 2015 at 22:01
  • What if you compile in a 64 bit envirinment? Your ptr might be 64 bits, but size might only be 32 bits. The alignment variable x might help to align to a 64 bit boundary which might have some kind of use if you have an a array of the union. –  Henrik Carlqvist Commented Jan 30, 2015 at 22:01
  • 2 @HenrikCarlqvist: In that case, long is unlikely to need stronger alignment than a union-pointer. –  Deduplicator Commented Jan 30, 2015 at 22:10

That's a very old book. At the time a pointer on many machines was only 16-bits, and a long was 32-bits, so the union forced alignment to 32-bits.

And as @Deduplicator points out, there are still many embedded systems that use 16-bit pointers.

Edit in response to the comment: The topic of alignment is fairly broad and full of nuance. To keep things simple, the discussion that follows makes these assumptions

  • pointers are 16-bits
  • int is 16-bits
  • long is 32-bits
  • the processor has strict alignment requirements, i.e. 16-bit values can only be accessed on 2-byte boundaries, 32-bit values can only be accessed on 4-byte boundaries.

The following structure would occupy 32-bits

However, the fields within the structure are still 16-bits each. Therefore, the alignment requirement is still only 16-bits. So for example, placing the structure at address 0xAA02 would be perfectly valid since ptr would be at an aligned address (0xAA02) and size would also be at an aligned address (0xAA04).

However, the address 0xAA02 is not suitably aligned for the union, since the x field of the union requires 32-bit alignment. Thus, placing the structure into a union with x forces the compiler to place the structure on a 4-byte boundary, when otherwise it could be placed on a 2-byte boundary.

user3386109's user avatar

  • 2 And that's still the case on most systems. Remember desktops, smartphones and tablets are the exception, and even they contain many smaller embedded chips. –  Deduplicator Commented Jan 30, 2015 at 21:58
  • @Deduplicator True, I neglected to consider the processor in my toaster :) –  user3386109 Commented Jan 30, 2015 at 22:03
  • Well in that case, wouldn't that add up to 32-bits? An int is 16-bits and a pointer is 16-bits so that adds up to 32-bits. Doesn't that eliminate the need for long? I just don't see how adding the long type helps when the struct size is equal or larger than the long type. –  George Newton Commented Jan 30, 2015 at 23:17
  • Exactly my question. I was wondering how a long forces alignment while a pointer is 64 bits (for newly built computers in 2017). The answers helped a lot. –  funct7 Commented Sep 8, 2017 at 1:28

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c alignment unions or ask your own question .

  • The Overflow Blog
  • Best practices for cost-efficient Kafka clusters
  • The hidden cost of speed
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Would an LEO asking for a race constitute entrapment?
  • How to securely connect to an SSH server that doesn't have a static IP address?
  • Is it safe to install programs other than with a distro's package manager?
  • Light switch that is flush or recessed (next to fridge door)
  • Will a Cavalier's mount grow upon maturity if it already grew from the dedication?
  • If a Palestinian converts to Judaism, can they get Israeli citizenship?
  • Word for when someone tries to make others hate each other
  • What is the difference between passing NULL vs. nullptr to a template parameter?
  • Movie from 80s or 90s about a helmet which allowed to detect non human people
  • In what instances are 3-D charts appropriate?
  • Asked to suggest referees 9 months after submission: what to do?
  • Why doesn’t dust interfere with the adhesion of geckos’ feet?
  • When can the cat and mouse meet?
  • What should I do if my student has quarrel with my collaborator
  • Getting an UK Visa with Ricevuta
  • Do all instances of a given string get replaced under a rewrite rule?
  • Using rule-based symbology for overlapping layers in QGIS
  • Can it be acceptable to take over CTRL + F shortcut in web app
  • Is the front wheel supposed to turn 360 degrees?
  • Largest number possible with +, -, ÷
  • Escape from the magic prison
  • How should I tell my manager that he could delay my retirement with a raise?
  • What are the consequences of making people's life choices publically tradable on a stock market?
  • How to change upward facing track lights 26 feet above living room?

union assignment in c

IMAGES

  1. What is Union in C Programming?

    union assignment in c

  2. Union in C

    union assignment in c

  3. Union in C Programming with examples

    union assignment in c

  4. C Program to Show the Simple Example of Union

    union assignment in c

  5. UNION IN C WITH EXAMPLE- 98

    union assignment in c

  6. What Is Difference Between Structure And Union In C With Example

    union assignment in c

VIDEO

  1. Assignment Operator in C Programming

  2. Assignment Operator in C Programming

  3. Augmented assignment operators in C

  4. Union Pacific Conductor Training Movie

  5. Epic Principal Speech

  6. Trade Union

COMMENTS

  1. C Unions

    C Unions. The Union is a user-defined data type in C language that can contain elements of the different data types just like structure. But unlike structures, all the members in the C union are stored in the same memory location. Due to this, only one member can store data at the given instance.

  2. C union assignment

    b = a; It's totally OK to do this. For structures and unions, assigning one to another of the same type is well-defined by the standard, and it's guaranteed that after the assignment, they should contain exactly the same data (padding excluded, if present). answered Nov 22, 2017 at 8:55. iBug.

  3. C Unions (With Examples)

    Here, the size of sJob is 40 bytes because. However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the above example, the size of its largest element, (name[32]), is 32 bytes. With a union, all members share the same memory.

  4. Unions (GNU C Language Manual)

    Unions (GNU C Language Manual) Packing With Unions Structure Assignment Structures Contents Index. 15.14 Unions. A union type defines alternative ways of looking at the same piece of memory. Each alternative view is defined with a data type, and identified by a name. A union definition looks like this:

  5. Unions in C

    A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purpose. All the members of a union share the ...

  6. Difference Between Structure and Union in C

    Union in C is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. ... The two structures or unions in the assignment must have the same members and member types.

  7. Union in C Programming

    Enumerated Union in C Programming An enumerated union is a data structure in C programming that combines the features of both unions and enumerations. Like a union, an enumerated union has a single memory location that can store any of its members. However, like an enumeration, the members of an enumerated union are named constants.

  8. Union declaration

    A union is a type consisting of a sequence of members whose storage overlaps (as opposed to struct, which is a type consisting of a sequence of members whose storage is allocated in an ordered sequence). The value of at most one of the members can be stored in a union at any one time. The type specifier for a union is identical to the struct ...

  9. Union declaration

    Trivial move constructor, move assignment operator, (since C++11) copy constructor and copy assignment operator of union types copy object representations. If the source and the destination are not the same object, these special member functions start lifetime of every object (except for objects that are neither subobjects of the destination nor of implicit-lifetime type) nested in the ...

  10. How to Use C Structures, Unions and Bit Fields with Examples

    Well, the difference lies in the size. If the above example would have been a structure, the size of structure would have been : sizeof (char) + sizeof (unsigned int) ie 1 + 4 = 5 bytes. But, in case of a union, the size is equivalent to that of the largest member type in union.

  11. Anonymous Union and Structure in C

    Following is a complete working example of anonymous union. C // C Program to demonstrate working of anonymous union #include <stdio.h> struct Scope {// Anonymous union union ... Explanation: Both of the above: In C, both equality comparison (==) and assignment (=) operators can be applied to structure variables, allowing for comparison and ...

  12. C Unions

    Union is a user-defined data type in C, which stores a collection of different kinds of data, just like a structure. However, with unions, you can only store information in one field at once. This tutorial guides you on how to use Union in C Programming. Union is like struct, except it uses less memory. The keyword union is used to declare the ...

  13. Unions in C Programming: Definition & Example

    Unions in C programming. Union is a data type in C programming that allows different data types to be stored in the same memory locations. Union provides an efficient way of reusing the memory ...

  14. Struct and union initialization

    When initializing a union, the initializer list must have only one member, which initializes the first member of the union unless a designated initializer is used ... In C, the braced list of initializers cannot be empty (note that C++ allows empty lists, and also note that a struct in C cannot be empty):

  15. PDF CS261: A Second Course in Algorithms Lecture #18: Five Essential Tools

    Theorem 2.1 The expected number of clauses satis ed by a random truth assignment, cho-sen uniformly at random from all 2n truth assignments, is 7 8 m. Since the optimal solution can't possibly satisfy more than mclauses, we conclude that the algorithm that chooses a random assignment is a 7 8-approximation (in expectation).

  16. PDF CS167: Reading in Algorithms The Algorithmic Lov asz Local Lemma

    Proof: Suppose clause C is satis ed by the current variable assignment when Fix(C) is called. If C shares a variable with C, then Lemma 4.1 implies that Fix(C) can only terminate with a truth assignment that satis es C. If C shares no variables with C, then randomly reassigning C's variables cannot make C violated. Inductively, calls to Fix(D)

  17. PDF BARGAINING UNITS 1, 3, 4, 11, 14, 15, 17, 20, AND 21 MASTER ...

    Agreement Between STATE OF CALIFORNIA and SERVICE EMPLOYEES INTERNATIONAL UNION (SEIU) - LOCAL 1000 covering BARGAINING UNITS 1, 3, 4, 11, 14, 15, 17, 20, AND 21

  18. One Dead After Single-Vehicle Crash in Union County

    ALTO PASS, Ill. -- One person is dead after a vehicle crash in Union County on Wednesday. A member with the Illinois State Police tells News 3 the crash happened along Illinois 127 near Mt. Glen ...

  19. Workers at General Motors joint venture battery plant in Tennessee

    About 1,000 workers at a General Motors joint venture electric vehicle battery plant in Spring Hill will get big pay raises now that they have joined the UAW union.

  20. C++ Unions

    C++ Unions. In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory separately for each member variable.

  21. SEIU Local 521

    Who We Are We represent 50,000 public and nonprofit, private-sector workers in the central Bay Area region and in the Central Valley. At SEIU Local 521, our mission is to provide our members with a voice in the workplace, in their union and in the larger community. Through our actions, we intend to create a more just and humane society.

  22. Member Benefits

    A Union is more than the workers themselves. Workers who join together for a common cause and for common interests have strength, more strength than they can ever achieve individually. California State Bargaining Unit 12 exists to protect and advance individual and collective rights in wages, benefits, hours of work, and working conditions for ...

  23. c

    CommentedJun 17, 2010 at 15:55. 1 Answer. Sorted by: 41. The start of each element is aligned with the address of the union itself. so the individual comparisons in the expression you ask about are true, but the expression as a whole is false unless the union is located at address 0x0001. The deleted text applied to the following comparisons:

  24. Workers at General Motors joint venture battery plant in Tennessee

    But the union lost its first organizing vote in May at a Mercedes assembly plant and other facilities near Tuscaloosa, Alabama. Spring Hill is the second GM joint venture battery plant to join the union and fall under the national contract. Workers at a plant near Warren, Ohio, voted to join the union in 2022.

  25. Dumfries and Galloway school week chnages are 'headache'

    A union has hit out at plans to change the school week in Dumfries and Galloway to finish early on Fridays. Unison said the move to an four-and-a-half day week would affect work and childcare ...

  26. CWA ends mediation with AT&T

    More than 17,000 workers with the union, the Communication Workers of America (CWA), across nine states are protesting what they call unfair labor practices at AT&T.

  27. C Unions (With Examples)

    Here, the size of sJob is 40 bytes because. However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the above example, the size of its largest element, (name[32]), is 32 bytes. With a union, all members share the same memory.

  28. Felix Jones' England exit 'deeply disappointing'

    Felix Jones' resignation as England defence coach after only seven months is "deeply disappointing", Rugby Football Union chief executive Bill Sweeney said as he confirmed the Irishman's departure.

  29. Kansas among worst places to work in U.S, new ranking says

    A report by Oxfam compares all 50 states, Puerto Rico and D.C. on worker rights, union laws and the minimum wage. See how Missouri fared. Local Kansas ranked among the worst places to work in the ...

  30. C alignment in union

    In the K&R C programming code, the following code is given. struct {. union header *ptr; /* next block if on free list */. unsigned size; /* size of this block */. } s; Align x; /* force alignment of blocks */. Then it goes on to say that "The Align field is never used; it just forces each header to be aligned on a worst-case boundary".