C: Where is union practically used?

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 … Read more

Is it allowed to use unions for type punning, and if not, why?

To re-iterate, type-punning through unions is perfectly fine in C (but not in C++). In contrast, using pointer casts to do so violates C99 strict aliasing and is problematic because different types may have different alignment requirements and you could raise a SIGBUS if you do it wrong. With unions, this is never a problem. … Read more

Is there any difference between structure and union if we have only one member?

In C: None. The famous “space-saving joke” #define struct union is almost not a joke. In C++98: Unions can only have POD members, non-union classes can have arbitrary members. In C++11: Unions can have arbitrary data members of object type (but not of reference type), but their use is more restricted that that of non-union … Read more

Why is it invalid for a union type declared in one function to be used in another function?

The example attempts to illustrate the paragraph beforehand1 (emphasis mine): 6.5.2.3 ΒΆ6 One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect … Read more