Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I do a `typedef` in C or C++, when should I add `_t` at the end of typedef'ed type? [duplicate]

Tags:

c++

c

typedef

I am confused when should I add the trailing _t to typedef'ed types?

For example, should I do this:

typedef struct image image_t; 

or this:

typedef struct image image; 

What are the general rules?

Another example, should I do this:

typdef enum { ARRAY_CLOSED, ARRAY_OPEN, ARRAY_HALFOPEN } array_type_t; 

or this:

typdef enum { ARRAY_CLOSED, ARRAY_OPEN, ARRAY_HALFOPEN } array_type; 

Please enlighten me.

Thanks, Boda Cydo.

like image 490
bodacydo Avatar asked Jul 12 '10 01:07

bodacydo


People also ask

Why do C types end in _t?

The _t usually wraps an opaque type definition. The requirement that additional types defined in this section end in "_t" was prompted by the problem of name space pollution. It is difficult to define a type (where that type is not one defined by POSIX.

How do we use typedef in C?

The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.

Which is correct about keyword typedef in C?

Explanation: The keyword typedef is used to give an alternate name to an existing data type. Hence hello is the new name for enum good.

Should you typedef structs in C?

PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs. Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.


2 Answers

In POSIX, names ending with _t are reserved, so if you are targeting a POSIX system (e.g., Linux), you should not end your types with _t.

like image 185
James McNellis Avatar answered Oct 04 '22 20:10

James McNellis


I personally despise the _t convention. So long as you are consistent, it really does not matter, however.

Note that (as other answers here indicate) if you are coding to some other standard, such as POSIX, you need to check if it's okay in that standard before using such names.

like image 28
Billy ONeal Avatar answered Oct 04 '22 21:10

Billy ONeal