CS157 Typedef
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.
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.
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;
typedef
in front.
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");
int count;
typedef
at the front: typedef int count;
typedef int count; // Right typedef count int; // WRONG WRONG WRONG!
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; }
stuct
, enum
, and union
, the syntax can be simplified.
typedef
.
typedef struct { int age; char name[30]; } person; // person is a data type, NOT a variable name int main() { person people[20]; return 0; }
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