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;
};

to have advantage of both possible definitions of point. Such a declaration is most convenient if you learned C++ first, where you may omit the struct keyword if the name 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 https://stackoverflow.com/documentation/c/2681/typedef

Feedback about page:

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



Table Of Contents