• Welcome to Jose's Read Only Forum 2023.
 

ProgEx19 - Using typedef With structs (typical C usage)

Started by Frederick J. Harris, November 07, 2009, 05:03:44 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frederick J. Harris


/*
  ProgEx19  -- Warning!  Another C program!  Set up as C project and save this
               file as Main.c

  Recall in ProgEx18 when we declared our struct variable of type Employee we
  had to do it like this...

  struct Employee emp;

  Well, there is a way around this in C, and it is one of the reasons I told you
  to start getting used to seeing typedefs.  If you preface the struct as in the
  program below with the typedef keyword, you can declare an instance of the
  Employee struct type just as with an ordinary variable, i.e.,

  Employee emp;

  This is not necessary in C++ - it was one of the changes made when C++ was
  created out of C, but since the Windows Api documentation is all in C, if you
  examine any of the C header files for the standard C Library functions or the
  Windows specific functions you'll see typedefs everywhere to circumvent this
  awkward variable declaration situation.  Run this program and you'll see it
  works exactly as the last.

  Shown below is an alternate code formatting method using the comma operator.
*/

#include <stdio.h>
#include <string.h>

typedef struct
{
char szName[32];
char szAddress[32];
char szCity[16];
char szState[16];
char szCountry[16];
char szZipCode[16];
unsigned int iAge;
unsigned int iEmpNum;
double dblSalary;
}Employee;

int main()
{
  Employee emp;

  strcpy(emp.szName,"Martin Veneski"),         printf("emp.szName        = %s\n",emp.szName);
  strcpy(emp.szAddress,"1016 Wabash Street"),  printf("emp.szAddress     = %s\n",emp.szAddress);
  strcpy(emp.szCity,"Shamokin"),               printf("emp.szCity        = %s\n",emp.szCity);
  strcpy(emp.szState,"PA"),                    printf("emp.szState       = %s\n",emp.szState);
  strcpy(emp.szCountry,"USA"),                 printf("emp.szCountry     = %s\n",emp.szCountry);
  strcpy(emp.szZipCode,"17872"),               printf("emp.szZipCode     = %s\n",emp.szZipCode);
  emp.iAge=23,                                 printf("emp.iAge          = %u\n",emp.iAge);
  emp.iEmpNum=123456,                          printf("emp.iEmpNum       = %u\n",emp.iEmpNum);
  emp.dblSalary=45000,                         printf("emp.dblSalary     = %6.2f\n",emp.dblSalary);
  getchar();

  return 0;
}

/*  Output
======================================
emp.szName        = Martin Veneski
emp.szAddress     = 1016 Wabash Street
emp.szCity        = Shamokin
emp.szState       = PA
emp.szCountry     = USA
emp.szZipCode     = 17872
emp.iAge          = 23
emp.iEmpNum       = 123456
emp.dblSalary     = 45000.00
*/