I am getting confused with typedef can anyone transcribe this to a normal composition? of structures? I really don't want to handle typedef since it's gets me confuse
struct stackNode
{
int data;
struct stackNode *nxtptr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
is
开发者_C百科typedef struct stackNode StackNode;
is the same as struct stackNode StackNode
and typedef StackNode *StackNodePtr;
is the same as struck stackNode *StackNodePtr
??
If you don't want to use typedef
you can always use full type name:
Instead of:
StackNode sn;
You would use:
struct stackNode sn;
Instead of:
StackNodePtr snp;
You would use:
struct stackNode *snp;
The declarations are exactly the same.
A more common way to write the very same would be:
typedef struct stackNode
{
int data;
struct stackNode *nxtptr;
} StackNode_t;
where stackNode
is the so called "struct tag" and StackNode_t
is the actual name of the type. If you declare structs like this, the rest of the program won't need to concern itself with the struct tag, and you can use nxtptr as if it was of StackNode_t.
typedef struct stackNode { int data; struct stackNode *nxtptr; } StackNode_t;
If you do not want to have "struct stackNode" inside the struct, I found that I am able to do this:
typedef struct STACKNODE STACKNODE;
typedef struct STACKNODE
{
int data;
STACKNODE *nxtptr;
};
That you could code such a thing, AND it compiles just fine, AND it runs just fine may seem counter intuitive. It can be counter intuitive because I'm using the same name for struct STACKNODE and the typedef STACKNODE. And further, I am typedef-ing the struct before it exists as a definition. Nevertheless, I have found that I can do this with Microsoft's C through many versions to today and Borland C (way back then).
I like it because if I am already going to typedef the struct, I don't like resorting to "struct STACKNODE *nxtptr" (i.e. using the word "struct") inside the struct definition.
With typedef, you define StackNode to be struct stackNode, and the Pointer StackNodePtr to be StackNode.
So what is not clear?
Well, to explain it easily: Typedef does basically nothing else then to tell the compiler that you create a new type of variables (such as int, char etc..)
The main reasons why to use typedef are
- Mnemonic names. This is often used in the library functions as well. Instead of using a standard type like int or long you can just typedef it into a size_t. So it's clearer what this variable is used for.
- Shortening names. Commonly used for things like structs (this would be your case). To avoid always having to type struct myStruct varname you can easily use a typedef to get rid of the struct in front.
see if typedef
helps. More like a 101. The section labelled "Usage concerns" may give some insights into your, er, concerns.
精彩评论