Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Where is union practically used?

Tags:

c++

c

unions

I have a example with me where in which the alignment of a type is guaranteed, union max_align . I am looking for a even simpler example in which union is used practically, to explain my friend.

like image 449
yesraaj Avatar asked Dec 23 '09 07:12

yesraaj


People also ask

What is practical use of union in C?

It is used to store different types of data in the same memory location. The only difference between structures and unions is that unions only hold one value at a time whereas structures hold all their members. With the help of unions, you can define many members but only one of them can contain value at one time.

Where are unions used?

Unions are mostly used in embedded programming where direct access to the memory is needed. Structs allocate enough space to store all of the fields in the struct. The first one is stored at the beginning of the struct, the second is stored after that, and so on.

What is the real time use of union?

The union can hold any kind of value, but only one at a time. That means it only takes up as much memory as the largest value (in the above case, the size of a pointer). What is union in programing language? In C, union is a datatype which allow you to use same memory address to store 2 or more different data types.

Why union is used in program?

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 location, as only one of its members can be accessed at a time. A union is used almost in the same way you would declare and use a structure.


1 Answers

I usually use unions when parsing text. I use something like this:

typedef enum DataType { INTEGER, FLOAT_POINT, STRING } DataType ;  typedef union DataValue {     int v_int;     float v_float;     char* v_string; }DataValue;  typedef struct DataNode {     DataType type;     DataValue value; }DataNode;  void myfunct() {     long long temp;     DataNode inputData;      inputData.type= read_some_input(&temp);      switch(inputData.type)     {         case INTEGER: inputData.value.v_int = (int)temp; break;         case FLOAT_POINT: inputData.value.v_float = (float)temp; break;         case STRING: inputData.value.v_string = (char*)temp; break;     } }  void printDataNode(DataNode* ptr) {    printf("I am a ");    switch(ptr->type){        case INTEGER: printf("Integer with value %d", ptr->value.v_int); break;        case FLOAT_POINT: printf("Float with value %f", ptr->value.v_float); break;        case STRING: printf("String with value %s", ptr->value.v_string); break;    } } 

If you want to see how unions are used HEAVILY, check any code using flex/bison. For example see splint, it contains TONS of unions.

like image 92
Yousf Avatar answered Oct 08 '22 19:10

Yousf