More on Structures, typedef, and Enumerated Types

Tom Kelliher, CS18

Mar. 11, 1996

Schedule for middle third of class.

Structures as Parameters and Return Values

Example: complex numbers

Form:

Formulas for:

Polar form conversion

New type definitions:

typedef  struct cmplx
         {
            double real;
            double imag;
         } complex;        // new type is complex

typedef  struct plr
         {
            double r;
            double theta;
         } polar;          // new type is polar
/**********************************************************************
 * convert --- convert the complex number c to polar form
 * needs math.h
 **********************************************************************/

polar convert(complex c)
{
   polar p;

   p.r = sqrt( c.real * c.real + c.imag * c.imag);

   if (c.real < EPSILON)   // too close to zero to permit division
   {
      if (c.imag < EPSILON)
         p.theta = 0.0;
      else if (c.imag > 0.0)
         p.theta = PI / 2.0;
      else
         p.theta = 3.0 * PI / 2.0;
   }
   // Note: atan() returns a result in [-PI/2, PI/2], affecting the
   // theta computations for quadrants 2, 3, and 4.
   else if (c.real > 0.0 && c.imag >= 0.0)   // point in quadrant 1
      p.theta = atan(c.imag / c.real);
   else if (c.real < 0.0)                    // point in quadrants 2 or 3
      p.theta = PI - atan(c.imag / c.real);
   else                                      // point in quadrant 4
      p.theta = 2 * PI + atan(c.imag / c.real);

   return p;
}

typedef

Used to name a new type or rename an old type:

Syntax:

typedef <TypeSpecifier> <Synonym>;

Enumerated Types

Collection of related symbolic constants.

Example: Path finding in a maze

2-D array representation of a maze:

enum MazeStates
{
   WALL;
   HALL;
   PATH;
   DEADEND;
   GOAL;
};

enum MazeStates maze[MAZE_HEIGHT][MAZE_WIDTH];

maze[0][0] = GOAL;

if (maze[i][j] == DEADEND)
   ;

maze[i][j] = 0;   // ok; not a good idea, though
int i = HALL      // ok; integral promotion

Typical boolean example:

enum Boolean
{
   FALSE = 0;
   TRUE = 1;
}

Boolean success;
...
if (success == TRUE)
   ;

Lab Exercise

For the example program involving the complex type, finish the program so that it compiles and correctly runs.



Thomas P. Kelliher
Fri Mar 8 12:14:03 EST 1996
Tom Kelliher