Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of Union in C [closed]

Tags:

c

unions

I'm looking for some union examples, not to understand how union works, hopefully I do, but to see which kind of hack people do with union.

So feel free to share your union hack (with some explanation of course :) )

like image 969
claf Avatar asked Apr 07 '09 08:04

claf


People also ask

What is the example of union in C?

We use the union keyword to define unions. Here's an example: union car { char name[50]; int price; }; The above code defines a derived type union car .

What is union explain with the help of example?

Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y. #include <stdio.h>

What are the types of union in C?

C - Unions. C - Bit Fields. C - Typedef. C - Input & Output. C - File I/O.


1 Answers

One classic is to represent a value of "unknown" type, as in the core of a simplistic virtual machine:

typedef enum { INTEGER, STRING, REAL, POINTER } Type;  typedef struct {   Type type;   union {   int integer;   char *string;   float real;   void *pointer;   } x; } Value; 

Using this you can write code that handles "values" without knowing their exact type, for instance implement a stack and so on.

Since this is in (old, pre-C11) C, the inner union must be given a field name in the outer struct. In C++ you can let the union be anonymous. Picking this name can be hard. I tend to go with something single-lettered, since it is almost never referenced in isolation and thus it is always clear from context what is going on.

Code to set a value to an integer might look like this:

Value value_new_integer(int v) {   Value v;   v.type = INTEGER;   v.x.integer = v;   return v; } 

Here I use the fact that structs can be returned directly, and treated almost like values of a primitive type (you can assign structs).

like image 50
unwind Avatar answered Sep 25 '22 10:09

unwind