Thursday, 1 May 2014


C++ allows us to define our own types based on other existing data types. In order to do that we shall use keyword typedef, whose form is:

typedefexisting_typenew_type_name ;

whereexisting_type is a C++ fundamental or any other defined type and new_type_name is the name that the new type we are going to define will receive. For example:

typedef char C;
typedef unsigned int WORD;
typedef char * string_t;
typedef char field [50];

In this case we have defined four new data types: C, WORD, string_t and field as char, unsigned int, char* and char[50] respectively, that we could perfectly use later as valid types:

C achar, anotherchar, *ptchar1;
WORD myword;
string_t ptchar2;
field name;

typedef can be useful to define a type that is repeatedly used within a program and it is possible that we will need to change it in a later version, or if a type you want to use has too long a name and you want it to be shorter.

Unions allow a portion of memory to be accessed as different data types, since all of them are in fact the same location in memory. Its declaration and use is similar to the one of structures but its functionality is totally different:
unionmodel_name {
  type1 element1;
  type2 element2;
  type3 element3;
} object_name;
All the elements of the union declaration occupy the same space of memory. Its size is the one of the greatest element of the declaration. For example:
unionmytypes_t {
char c;
float f;
  } mytypes;
defines three elements:
each one of a different data type. Since all of them are referring to a same location in memory, the modification of one of the elements will afect the value of all of them.
One of the uses a union may have is to unite an elementary type with an array or structures of smaller elements. For example,

long l;
struct {
short hi;
short lo;
    } s;
char c[4];
} mix;