|< C & C++ Type Specifiers 1 | Main | C++/OOP - Encapsulation 1 >| C-Extra | Microsoft C/Win32 | Site Index | Download |


 

 

 

 

 

MODULE 11a

THE C/C++ TYPE SPECIFIERS 2

struct, typedef, enum, union

 

 

 

 

 

 

 

My Training Period: xx hours

 

The struct lab worksheets are: C/C++ struct part 1 and C/C++ struct part 2. Also the combination of the struct, arrays, pointers and function C worksheet 1, C lab worksheet part 2 and C lab worksheet part 3.

 

11.5    typedef

  • In contrast to the class, struct, union, and enum declarations, typedef declaration do not introduce new type but introduces new name or creating synonym (or alias) for existing type.

  • The syntax is as follows:

typedef	type-declaration	the_synonym;
  • You cannot use the typedef specifier inside a function definition.

  • When declaring a local-scope identifier by the same name as a typedef, or when declaring a member of a structure or union in the same scope or in an inner scope, the type specifier must be specified. For example:

typedef float TestType;

 

int main()

{ ...  }

 

// function scope...

int MyFunct(int)

{

      // same name with typedef, it is OK

      int TestType;

}

  • When declaring a local-scope identifier by the same name as a typedef, or when declaring a member of a structure or union in the same scope or in an inner scope, the type specifier must be specified. For example:

// both declarations are different...

typedef float TestType;

const TestType r;

  • To reuse the TestType name for an identifier, a structure member, or a union member, the type must be provided, for example:

const    int    TestType;

  • Typedef names share the name space with ordinary identifiers. Therefore, a program can have a typedef name and a local-scope identifier by the same name.

// a typedef specifier
typedef char FlagType;
 
void main() 
{ ... }
 
void myproc(int) 
{
    int FlagType;
}

// a character type.

typedef    char CHAR;

 

// a pointer to a string (char *).

typedef    CHAR * THESTR;

// then use it as function parameter...

THESTR    strchr(THESTR source, CHAR destination);

 

typedef    unsigned    int    uint;

// equivalent to "unsigned int ui;"

uint    ui;

typedef char CHAR, *THESTR;

typedef void Funct(int, int);

Funct test;

void test(int, int);

typedef  struct Card Card;

typedef unsigned short USHORT;

typedef struct{

      char  *face;

      char  *suit;

} Card;

Card  deck[50];

// typedef and struct program example

#include <stdio.h>

 

typedef struct TestStruct

{

   int   p;

   char q;

   double r;

} mine;

 

void main()

{

  mine testvar; // the declaration becomes simpler

  testvar.p = 200;

  testvar.q = 'T';

  testvar.r = 1.234;

  printf("%d\n%c\n%.4f\n", testvar.p, testvar.q, testvar.r);

}

 

Output:

 

struct and typedef

// typedef specifier

#include <stdio.h>

 

typedef struct mystructtag

{

   int   x;

   double y;

   char* z;

} mystruct;

 

int main()

{

   mystruct Test1, *Test2;

   Test1.x = 111;

   Test1.y = 1.111;

   printf("Test1.x = %d\nTest1.y = %f\n", Test1.x, Test1.y);

  

   Test1.z = "This is a string";

   Test2 = &Test1;

   printf("Test1->z = %s\n", Test2->z);

   return 0;

}

 

Output:

 

typedef program example

 

11.6    enum - Enumeration Constants

// for definition of enumerated type
enum [tag] 
{
enum-list
} 
[declarator];
// for declaration of variable of type tag
enum tag declarator;

enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

enum days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};

enum days {Mon, Tue, Wed, Thu = 7, Fri, Sat, Sun};

#include <iostream>

using namespace std;

 

enum days {mon = 1,tue,wed,thu,fri,sat,sun};

 

void main()

{

    // declaring enum data type

    enum days day_count;

 

    cout<<" Simple day count\n";

    cout<<"    using enum\n";

 

    for(day_count=mon; day_count<=sun; day_count++)

    cout<<"  "<<day_count<<"\n";

}

 

Output:

 

enum program example

  • As said before, by default, the first enumerator has a value of 0, and each successive enumerator is one larger than the value of the previous one, unless you explicitly specify a value for a particular enumerator.

  • Enumerators needn't have unique values within an enumeration. The name of each enumerator is treated as a constant and must be unique within the scope where the enum is defined. An enumerator can be promoted to an integer value.

  • Converting an integer to an enumerator requires an explicit cast, and the results are not defined if the integer value is outside the range of the defined enumeration.

  • Enumerated types are valuable when an object can assume a known and reasonably limited set of values.

  • Another program example.

// enum declarations

#include <iostream>

using namespace std;

 

// declare enum data type Days

enum Days

{

    monday,             // monday = 0 by default

    tuesday = 0,       // tuesday = 0 also

    wednesday,       // wednesday = 1

    thursday,            // thursday = 2

    friday,                 // an so on.

    saturday,

    sunday

};

 

int main()

{

    // try changing the tuesday constant,

    // recompile and re run this program

    enum Days WhatDay = tuesday;

    switch (WhatDay)

    {

          case 0:

              cout<<"It's Monday"<<endl;

              break;

          default:

          cout<<"Other day"<<endl;

    }

return 0;

}

 

Output:

 

C and C++ enum program example

// is legal in C++

Days WhatDay = tuesday;

// enum definition

#include <iostream>

using namespace std;

 

enum FileOpenFlags

{

    // defined here...

    OpenReadOnly  = 1,

    // using OpenReadOnly as the next initializer and so on...

    OpenReadWrite = OpenReadOnly,

    OpenBinary = OpenReadWrite,

    OpenText = OpenBinary,

    OpenShareable = OpenText

};

 

int main()

{

    return 0;

}

// no output

// enumeration data type

#include <iostream>

using namespace std;

 

enum Days

{

   

    Tuesday,

    Wednesday,

    Thursday,

    Friday,

    Saturday,

           Sunday,

    Monday

};

 

int  i;

Days d = Thursday;

int main()

{

  // converted by integral promotion.

  i = d;

  cout<<"i = "<<i<<"\n";

  return 0;

}

 

Output:

 

more C and C++ enum program examples

// erroneous attempt to set d to Saturday.

d = 5;
// explicit cast-style conversion to type Days.
d = (Days)5;
// explicit function-style conversion to type Days.
d = Days(4);
d = Days(30);

// typedef and enum...

#include <stdio.h>

 

typedef enum {

  FailOpenDisk = 1,

  PathNotFound,

  FolderCannotBeFound,

  FileCannotBeFound,

  FailOpenFile,

  FileCannotBeRead,

  DataCorrupted

} ErrorCode;

 

int main(void)

{

ErrorCode MyErrorCode;

 

for(MyErrorCode=FailOpenDisk; MyErrorCode<=DataCorrupted; MyErrorCode++)

    printf(" %d", MyErrorCode);

printf("\n");

return 0;

}

 

Output:

 

C and C++ typedef and enum program example

 

11.7    union

union    sample

{

    int  p;

    float q;

};

union sample

{

    int  p;

    float q;

};

...

...

union sample content = {234};

union sample

{

    int  p;

    float q;

};

...

...

union sample content = {24.67};

  1. Assigning a union to another union of the same type.

  2. Taking the address (&) of a union and

  3. Accessing union member using the structure member operator and the structure pointer operator.

#include <iostream>

using namespace std;

 

union  sample

{

    int  p;

    float q;

    double r;

};

 

void main()

{

    // union data type

    union sample content;

 

    content.p = 37;

    content.q = 1.2765;

 

    cout<<"Display the union storage content\n";

    cout<<"      ONLY one at a time!\n";

    cout<<"---------------------------------\n";

    cout<<"Integer: "<<content.p<<"\n";

    cout<<"Float  : "<<content.q<<"\n";

    cout<<"Double : "<<content.r<<"\n";

    cout<<"See, some of the contents are rubbish!\n";

 

    content.q=33.40;

    content.r=123.94;

 

    cout<<"\nInteger: "<<content.p<<"\n";

    cout<<"Float  : "<<content.q<<"\n";

    cout<<"Double : "<<content.r<<"\n";

    cout<<"See another inactive contents, rubbish!\n";

    cout<<"\nBetter use struct data type!!\n";

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------

 

C and C++ struct vs union program example

// typedef specifier

#include <cstdio>

 

// typedef oldname newname

typedef struct mystructtag

{

   int   x;

   double y;

   char* z;

} mystruct;

 

int main()

{

   mystruct Test1, *Test2;

   Test1.x = 111;

   Test1.y = 1.111;

   printf("Test1.x = %d\nTest1.y = %f\n", Test1.x, Test1.y);

  

   Test1.z = "This is a string";

   Test2 = &Test1;

   printf("Test1->z = %s\n",Test2->z);

   return 0;

}

 

Output:

 

struct typedef enum union Visual C++ program example

/////// typestruct.cpp ///////////

// typedef specifier

#include <cstdio>

using namespace std;

 

// typedef oldname newname

typedef struct mystructtag

{

   int   x;

   double y;

   char* z;

} mystruct;

 

int main()

{

   mystruct Test1, *Test2;

   Test1.x = 111;

   Test1.y = 1.111;

   printf("Test1.x = %d\nTest1.y = %f\n", Test1.x, Test1.y);

  

   Test1.z = "This is a string";

   Test2 = &Test1;

   printf("Test1->z = %s\n", Test2->z);

   return 0;

}

 

[bodo@bakawali ~]$ g++ typestruct.cpp -o typestruct

[bodo@bakawali ~]$ ./typestruct

 

Test1.x = 111

Test1.y = 1.111000

Test1->z = This is a string

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

Further C & C++ related reading and digging:

 

  1. The struct lab worksheets for your practice are: C/C++ struct part 1 and C/C++ struct part 2.
  2. Also the combination of the struct, arrays, pointers and function C worksheet 1, C lab worksheet part 2 and C lab worksheet part 3.
  3. Check the best selling C/C++ books at Amazon.com.

 

 

 

 

 

 

|< C & C++ Type Specifiers 1 | Main | C++/OOP - Encapsulation 1 >| C-Extra | Microsoft C/Win32 | Site Index | Download |


C and C++ Type Specifiers:  Part 1 | Part 2 |