C – Union – POFTUT

C – Union

[rps-include post=6557]

Union is a data type used to store different type of variables. Union is very similar to the struct but have some differences those have explained below. Union can contain int,char,float,… etc. in a single block. One union can contain single set of data at a time.

Defining Unions

Defining union is very similar to struct. We will use union statement. After union statement we will put union tag. After the tag we can put variables in curly brackets. Union tag is optional. Union variables will be automatically instantiated.

In this example we will define an union named MyData and a variable mydata.

After union definition we should also initialize some variable which is in union MyData type. We will initialize variable named mydata

Accessing Members

In this part we will access to the union members by using the name of the union variable and the member name. We can use this method both set and get member data. We will put a point between the union variable name and union member name like below.

Below we can see an example where member variables data is set and get.

echo '

Structures vs Unions

As stated previously struct and union have syntax similarities. But the biggest difference is struct variables holds their members in separate memory areas but all same union variables will hold same memory areas. Simply single union type will hold single data for all union variables for the same type.

[rps-include post=6557]

Leave a Reply

Your email address will not be published. Required fields are marked *