Typedef Structs

suggest change

Combining typedef with struct can make code clearer. For example:

typedef struct 
{
    int x, y;
} Point;

as opposed to:

struct Point 
{
    int x, y;
};

could be declared as:

Point point;

instead of:

struct Point point;

Even better is to use the following

typedef struct Point Point;

struct Point 
{
    int x, y;
};

so that both Point and struct Point name the type. That is convenient in a header shared with C++, where the tag is also a type name if it is not ambiguous.

typedef names for structs could be in conflict with other identifiers of other parts of the program. Some consider this a disadvantage, but for most people having a struct and another identifier the same is quite disturbing. Notorious is e.g POSIX’ stat

int stat(const char *pathname, struct stat *buf);

where you see a function stat that has one argument that is struct stat.

typedef’d structs without a tag name always impose that the whole struct declaration is visible to code that uses it. The entire struct declaration must then be placed in a header file.

Consider:

#include "bar.h"

struct foo 
{
    bar *aBar;
};

So with a typedefd struct that has no tag name, the bar.h file always has to include the whole definition of bar. If we use

typedef struct bar bar;

in bar.h, the details of the bar structure can be hidden.

See Typedef.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents