Unions in C
Unions in C
Definition
• union can be defined as a user-defined data type which is a collection of different
variables of different data types in the same memory location. The union can also
be defined as many members, but only one member can contain a value at a
particular point in time.
• union is a user-defined data type, but unlike structures, they share the same
memory location.
• Syntax:
keyword union unionName {
data_type Variablename;
data_type Variablename; members of union.
};
Declaring and Accessing variables
• We can declare a variable for the union so that we can access the member of
the union easily. There are two ways to declare union variable:
By . Dot operator.
The dot operator is used only when you are working with a union variable directly
(not a pointer to a structure).
Syntax:
unionVariable.membername;
• Arrow operator.
The arrow operator (->) in C is used to access members of a structure
through a union to that union. It's a shorthand for dereferencing a
pointer and then accessing the union member.
syntax: unionvariable->membername;
Ex: ptr->id = value;
• Without arrow(->) operator
(*ptr).id = value;
Typedef in Union
union student{
int rno;
float marks;
char name[20];
};
If we want to declare a union variable to student we have to follow this
union student s1,s2;
But we can avoid this with the use of typedef.
Syntax: typedef union union_name alias_name;
i.e typedef union student stud;
Here student remained as stud. So we can declare variables as
stud s1,s2;
Array of Unions
// Defining a structure
union Student {
int id;
float marks;
};
int main() {
// Dynamically allocate memory for a structure
union Student *ptr = (union Student *)malloc(sizeof(union Student));
// Assigning values using the pointer
ptr->id = 102;
ptr->marks = 92.5;
// Printing union members
printf("ID: %d\n", ptr->id);
printf("Marks: %.2f\n", ptr->marks);
// Freeing the allocated memory
free(ptr);
return 0;
}
Enumerations in C
• The enum in C is also known as the enumerated type. It is a user-defined data type
that consists of integer values, and it provides meaningful names to these values.
The use of enum in C makes the program easy to understand and maintain. The
enum is defined by using the enum keyword.
• enum variable consists a set of possible values.
• Syntax:
enum flag{integer_const1, integer_const2,.....integter_constN};
• Ex:
Enum fruits {mango,apple,guva,papaya};
In above example, compiler will assign values from 0 automatically. Or we can
assign values as for our needs.
Enumerated type declaration
• enum status{false,true};
• Why do we use enum
• The enum is used when we want our variable to have only a set of values. For
example, we create a direction variable. As we know that four directions exist
(North, South, East, West), so this direction variable will have four possible
values. But the variable can hold only one value at a time. If we try to provide
some different value to this variable, then it will throw the compilation error.
• The enum is also used in a switch case statement in which we pass the enum
variable in a switch parenthesis. It ensures that the value of the case block should
be defined in an enum.
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum days d;
d=monday;
switch(d)
{
case sunday:
printf("Today is sunday");
break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}
return 0;
}
Some Important points
• If we do not provide any value to the enum names, then the compiler will
automatically assign the default values to the enum names starting from 0.
• We can also provide the values to the enum name in any order, and the unassigned
names will get the default value as the previous one plus one.
• The values assigned to the enum names must be integral constant, i.e., it should
not be of other types such string, float, etc.
• All the enum names must be unique in their scope, i.e., if we define two enum
having same scope, then these two enums should have different enum names
otherwise compiler will throw an error.
Macro vs enum.
• Macro can also be used to define the name constants, but in case of an enum, all the name
constants can be grouped together in a single statement.
• For example.
# define pass 0;
# define success 1;
•
The above two statements can be written in a single statement by using the enum type.
enum status{pass, success};
• The enum type follows the scope rules while macro does not follow the scope rules.
• In Enum, if we do not assign the values to the enum names, then the compiler will
automatically assign the default value to the enum names. But, in the case of macro, the
values need to be explicitly assigned.
• The type of enum in C is an integer, but the type of macro can be of any type.
Bit-fields in C
• In C, we can specify the size (in bits) of the structure and union members. The
idea of bit-field is to use memory efficiently when we know that the value of a
field or group of fields will never exceed a limit or is within a small range. C Bit
fields are used when the storage of our program is limited.
• Need of Bit Fields in C
• Easy to Implement.
Declaration
Bit-fields are variables that are defined using a predefined width or size.
Syntax:
struct
{
data_type member_name : width_of_bit-field;
};
• Where,
• struct date
• {
• // month has value between 0 and 15,
• // so 4 bits are sufficient for month variable.
• int month : 4;
• };
Ex;
// C program to demonstrate use of Bit-fields
#include <stdio.h>
// Space optimized representation of the date
struct date {
// d has value between 0 and 31, so 5 bits
// are sufficient
int d : 5;
// m has value between 0 and 15, so 4 bits
// are sufficient
int m : 4;
int y;
};
int main()
{
printf("Size of date is %lu bytes\n",
sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
Output
Size of date is 8 bytes here actual size is 12 bytes because we taken 3 int
values but it given 8 because of bit-field.
Date is -1/-4/2014 the values are in negative because of signed int.
Thank you