Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef struct and declaring a structure variable

Tags:

c

ios

objective-c

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 ?

like image 962
Midhun MP Avatar asked Nov 23 '25 08:11

Midhun MP


1 Answers

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.

like image 110
unwind Avatar answered Nov 28 '25 04:11

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!