CS157: Intro to C, Part II

Spring 2018

Typedef

See this page as a slide show

Typedefs

CS157 Typedef

Horrible Code

Consider this horrible code:

float bal;
long acct;

What sort of values are in those variables? Who knows? Clearly, bal is a floating-point value, and acct is a big integer, but that’s all we know.

Somewhat Less Horrible Code

Now, consider this code:

money bal;
account_number acct;

That tells us more! We now know that bal is an amount of money, and that acct is an account number.

The Whole Picture

typedef float money;         // Make “money” an alias for “float”
typedef long account_number; // Make “account_nbumer” an alias for long

money bal;
account_number acct;

typedefs

typedef unsigned short ushort;
typedef char bigstring[256];

ushort shortie;             // same as unsigned short shortie;
bigstring name;             // same as char name[256];

shortie = 42;
strcpy(name, "hello");

Get the order right

  1. Write a normal declaration: int count;
  2. Add typedef at the front: typedef int count;
    typedef int count;		// Right
    typedef count int;		// WRONG WRONG WRONG!

typedefs

A typedef is a name for some type. Any type can be named with a typedef.

struct person_s {
    int age;
    char name[30];
};

typedef struct person_s person;

int main() {
    person people[20];        // instead of struct person
    return 0;
}

typedefs

typedef struct {
    int age;
    char name[30];
} person;
// person is a data type, NOT a variable name

int main() {
    person people[20];
    return 0;
}

typedef

Data type comes after closing squiggly for typedef

typedef struct {
    // stuff here
} dataTypeName;

Either define a type, or a variable, but not both:

typedef struct {
    // stuff here
} dataTypeName variableName;        // ERROR

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2016-07-24T15:31

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building