Notes on typedef and struct
This is my OLD blog. I've copied this post over to my NEW blog at:
http://www.saltycrane.com/blog/2007/02/notes-on-struct-and-typedef/
You should be redirected in 2 seconds.
Here are my notes on using C's
struct and
typedef keywords.struct
To create a C structure, first create a new structure type:struct my_struct_tag
{
int member1;
float member2;
};
Note that in the example above, the struct keyword is used only to
create a new data type but it has not defined any variables yet.To define new varaibles of this structure type, do this:
struct my_struct_tag mystruct1; struct my_struct_tag mystruct2;
You can optionally combine these two steps and create the new data type and define variables:
struct my_struct_tag
{
int member1;
float member2;
} mystruct1, mystruct2;
In this case the structure tag my_struct_tag is optional.typedef
From the K&R book, thetypedef keyword is used to create new data type names. For example:typedef int Length;
The name
Length is a synonym for int and can be used as follows:
Length len, maxlen;
The
typedef keyword can also be used to rename struct data types.
Using the example above:
typedef struct my_struct_tag MyStructType; MyStructType mystruct1; MyStructType mystruct2;This creates a new data type name,
MyStructType which is synonymous with
the struct my_struct_tag data type, and then defines two variables,
mystruct1 and mystruct2.You could combine the creation of the type name with the creation of the struct data type:
typedef struct my_struct_tag
{
int member1;
float member2;
} MyStructType;
Like the previous example, this creates a new structure data type
and creates a new type name, MyStructType which is synonymous with
struct my_struct_tag. Like the combo example in
the struct section above, the structure tag, my_struct_tag is optional.
However, unlike that example, the identifier following the last curly brace
(MyStructType) is the new type name and not a new variable. To define
the variables, use:MyStructType mystruct1; MyStructType mystruct2;See also How to share non-global C data structures
Technorati tags: c
No comments:
Post a Comment