简体   繁体   中英

typedef struct and declaring a structure variable

Currently I'm working on an iOS application, in which I'm using structure for storing some data.

I declared an structure like:

typedef struct Message
{
    int    messageType;
    char   *data;
    int    length;
} Message;

But when I need to declare a variable I accidentally wrote like:

struct Message *myMessage = NULL;

This is working fine, no issues.

My question is why this line not displaying any issues ?

Both :

struct Message *myMessage = NULL;

and

Message *myMessage = NULL;

Working correctly. Is this correct behavior of typedef ? Why it won't display any error when I used struct Message ?

Yes, it's correct.

The name following the keyword struct , called the "struct tag", is not in the same "name space" as the typedef alias name. That's why they're not colliding and generating some kind of error.

That said, you should remove the tag from your declaration, and just make it:

typedef struct
{
    int    messageType;
    char   *data;
    int    length;
} Message;

No point in introducing names that are not needed, and that would also protect you from this kind of confusion since there would be no name to write struct before.

Yes, this is expected. struct Message is a type, and your typedef has created Message as an alias for it. You can use either when declaring variables.

The above declares both struct Message and its "alias" as Message . Both is fine.

这是typedef的正确行为。

May be that is why, We have been suggested to follow the naming convention for typedef as I said above.

struct Message {  
    int messageType;  
    char *data;  
    int length;  
}Message_t;  

Above is the good practice to declare struct with their typedef . And in embedded you will usually find it to be, Message_Type .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM