Why should we typedef a struct so often in C?
I have seen many programs consisting of structures like the one below
typedef struct
{
int i;
char k;
} elem;
elem user;
Why is it needed so often? Any specific reason or applicable area?
c struct typedef
add a comment |
I have seen many programs consisting of structures like the one below
typedef struct
{
int i;
char k;
} elem;
elem user;
Why is it needed so often? Any specific reason or applicable area?
c struct typedef
13
More thorough and precise answer: stackoverflow.com/questions/612328/…
– AbiusX
Mar 17 '11 at 2:14
It has disadvantages I think you can't create a link list with anonymous struct because the linestruct * ptr
inside the struct will cause error
– Raghib Ahsan
Feb 1 '16 at 17:40
5
The 'more thorough and precise answer' is Difference between struct and typedef struct in C++, and there are significant differences between C and C++ in this area which make that answer not wholly appropriate for a question about C.
– Jonathan Leffler
Jun 5 '16 at 22:21
This question has a duplicate typedef struct vs struct definitions that also has stellar answers.
– Jonathan Leffler
Jun 5 '16 at 22:25
OTOH, kernel.org/doc/html/v4.10/process/coding-style.html tells us that we shouldn't do such typedefs.
– glglgl
Mar 27 '18 at 15:52
add a comment |
I have seen many programs consisting of structures like the one below
typedef struct
{
int i;
char k;
} elem;
elem user;
Why is it needed so often? Any specific reason or applicable area?
c struct typedef
I have seen many programs consisting of structures like the one below
typedef struct
{
int i;
char k;
} elem;
elem user;
Why is it needed so often? Any specific reason or applicable area?
c struct typedef
c struct typedef
edited Mar 18 '16 at 1:28
nbro
5,787105198
5,787105198
asked Oct 31 '08 at 7:14
Manoj DoubtsManoj Doubts
6,032133642
6,032133642
13
More thorough and precise answer: stackoverflow.com/questions/612328/…
– AbiusX
Mar 17 '11 at 2:14
It has disadvantages I think you can't create a link list with anonymous struct because the linestruct * ptr
inside the struct will cause error
– Raghib Ahsan
Feb 1 '16 at 17:40
5
The 'more thorough and precise answer' is Difference between struct and typedef struct in C++, and there are significant differences between C and C++ in this area which make that answer not wholly appropriate for a question about C.
– Jonathan Leffler
Jun 5 '16 at 22:21
This question has a duplicate typedef struct vs struct definitions that also has stellar answers.
– Jonathan Leffler
Jun 5 '16 at 22:25
OTOH, kernel.org/doc/html/v4.10/process/coding-style.html tells us that we shouldn't do such typedefs.
– glglgl
Mar 27 '18 at 15:52
add a comment |
13
More thorough and precise answer: stackoverflow.com/questions/612328/…
– AbiusX
Mar 17 '11 at 2:14
It has disadvantages I think you can't create a link list with anonymous struct because the linestruct * ptr
inside the struct will cause error
– Raghib Ahsan
Feb 1 '16 at 17:40
5
The 'more thorough and precise answer' is Difference between struct and typedef struct in C++, and there are significant differences between C and C++ in this area which make that answer not wholly appropriate for a question about C.
– Jonathan Leffler
Jun 5 '16 at 22:21
This question has a duplicate typedef struct vs struct definitions that also has stellar answers.
– Jonathan Leffler
Jun 5 '16 at 22:25
OTOH, kernel.org/doc/html/v4.10/process/coding-style.html tells us that we shouldn't do such typedefs.
– glglgl
Mar 27 '18 at 15:52
13
13
More thorough and precise answer: stackoverflow.com/questions/612328/…
– AbiusX
Mar 17 '11 at 2:14
More thorough and precise answer: stackoverflow.com/questions/612328/…
– AbiusX
Mar 17 '11 at 2:14
It has disadvantages I think you can't create a link list with anonymous struct because the line
struct * ptr
inside the struct will cause error– Raghib Ahsan
Feb 1 '16 at 17:40
It has disadvantages I think you can't create a link list with anonymous struct because the line
struct * ptr
inside the struct will cause error– Raghib Ahsan
Feb 1 '16 at 17:40
5
5
The 'more thorough and precise answer' is Difference between struct and typedef struct in C++, and there are significant differences between C and C++ in this area which make that answer not wholly appropriate for a question about C.
– Jonathan Leffler
Jun 5 '16 at 22:21
The 'more thorough and precise answer' is Difference between struct and typedef struct in C++, and there are significant differences between C and C++ in this area which make that answer not wholly appropriate for a question about C.
– Jonathan Leffler
Jun 5 '16 at 22:21
This question has a duplicate typedef struct vs struct definitions that also has stellar answers.
– Jonathan Leffler
Jun 5 '16 at 22:25
This question has a duplicate typedef struct vs struct definitions that also has stellar answers.
– Jonathan Leffler
Jun 5 '16 at 22:25
OTOH, kernel.org/doc/html/v4.10/process/coding-style.html tells us that we shouldn't do such typedefs.
– glglgl
Mar 27 '18 at 15:52
OTOH, kernel.org/doc/html/v4.10/process/coding-style.html tells us that we shouldn't do such typedefs.
– glglgl
Mar 27 '18 at 15:52
add a comment |
15 Answers
15
active
oldest
votes
As Greg Hewgill said, the typedef means you no longer have to write struct
all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef
, is the case I guess.
Also note that while your example (and mine) omitted naming the struct
itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
typedef struct Point Point;
Point * point_new(int x, int y);
and then provide the struct
definition in the implementation file:
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of typedef
to hide struct
is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
53
You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).
– dreamlax
Jan 6 '11 at 10:40
11
@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.
– brianmearns
Jan 16 '12 at 17:08
9
It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.
– William Pursell
Jan 25 '12 at 14:15
7
@Rerito fyi, page 166 of C99 draft, All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use. And All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
– Ring Ø
Apr 15 '13 at 4:41
9
Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle
– gsingh2011
May 29 '13 at 0:13
|
show 20 more comments
It's amazing how many people get this wrong. 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.
Consider:
#ifndef FOO_H
#define FOO_H 1
#define FOO_DEF (0xDEADBABE)
struct bar; /* forward declaration, defined in bar.h*/
struct foo {
struct bar *bar;
};
#endif
With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF
definition. If it doesn't attempt to dereference the 'bar' member of the foo
struct then there will be no need to include the "bar.h" file.
Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:
struct foo *foo;
printf("foo->bar = %p", foo->bar);
Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.
If I have to maintain your code, I will remove your typedef'd structs.
32
What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
– William Pursell
Jan 25 '12 at 14:04
27
Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.
– Jens
Mar 14 '12 at 10:31
30
The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle
– jasso
Dec 9 '12 at 22:39
55
What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to usetypedef struct X { ... } X
. That way you can use the short formX
to address the struct anywhere the definition is available, but can still forward-declare and usestruct X
when desired.
– Pavel Minaev
Mar 20 '13 at 7:18
6
I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.
– Nathan Day
Jun 1 '13 at 10:26
|
show 7 more comments
From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):
The C language rules for naming
structs are a little eccentric, but
they're pretty harmless. However, when
extended to classes in C++, those same
rules open little cracks for bugs to
crawl through.
In C, the name s appearing in
struct s
{
...
};
is a tag. A tag name is not a type
name. Given the definition above,
declarations such as
s x; /* error in C */
s *p; /* error in C */
are errors in C. You must write them
as
struct s x; /* OK */
struct s *p; /* OK */
The names of unions and enumerations
are also tags rather than types.
In C, tags are distinct from all other
names (for functions, types,
variables, and enumeration constants).
C compilers maintain tags in a symbol
table that's conceptually if not
physically separate from the table
that holds all other names. Thus, it
is possible for a C program to have
both a tag and an another name with
the same spelling in the same scope.
For example,
struct s s;
is a valid declaration which declares
variable s of type struct s. It may
not be good practice, but C compilers
must accept it. I have never seen a
rationale for why C was designed this
way. I have always thought it was a
mistake, but there it is.
Many programmers (including yours
truly) prefer to think of struct names
as type names, so they define an alias
for the tag using a typedef. For
example, defining
struct s
{
...
};
typedef struct s S;
lets you use S in place of struct s,
as in
S x;
S *p;
A program cannot use S as the name of
both a type and a variable (or
function or enumeration constant):
S S; // error
This is good.
The tag name in a struct, union, or
enum definition is optional. Many
programmers fold the struct definition
into the typedef and dispense with the
tag altogether, as in:
typedef struct
{
...
} S;
The linked article also has a discussion about how the C++ behavior of not requireing a typedef
can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef
your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef
the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.
4
Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.
– user2061057
Mar 3 '16 at 15:19
2
One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with theint stat(const char *restrict path, struct stat *restrict buf)
function. There you have a functionstat
in the ordinary name space andstruct stat
in the tag name space.
– Jonathan Leffler
Jun 5 '16 at 22:02
1
your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check
– eRaisedToX
Aug 3 '16 at 7:24
"declarations such as .. are errors in C" Why? It isn't in C++ or C#. Why is C designed this way?
– Aaron Franke
Nov 16 '18 at 7:00
add a comment |
Using a typedef
avoids having to write struct
every time you declare a variable of that type:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
1
ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?
– Manoj Doubts
Oct 31 '08 at 12:03
4
Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.
– Michael Carman
Oct 31 '08 at 13:05
37
It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.
– Herms
Oct 31 '08 at 19:36
3
unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.
– user3629249
May 28 '15 at 20:50
add a comment |
One other good reason to always typedef enums and structs results from this problem:
enum EnumDef
{
FIRST_ITEM,
SECOND_ITEM
};
struct StructDef
{
enum EnuumDef MyEnum;
unsigned int MyVar;
} MyStruct;
Notice the typo in EnumDef in the struct (EnuumDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.
With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:
typedef
{
FIRST_ITEM,
SECOND_ITEM
} EnumDef;
typedef struct
{
EnuumDef MyEnum; /* compiler error (unknown type) */
unsigned int MyVar;
} StructDef;
StrructDef MyStruct; /* compiler error (unknown type) */
I would advocate ALWAYS typedef'ing structs and enumerations.
Not only to save some typing (no pun intended ;)), but because it is safer.
Even worse, your typo might coincide with a different tag. In the case of a struct this could result in the entire program compiling correctly and having runtime undefined behaviour.
– M.M
Feb 14 '15 at 22:15
3
this definition: 'typedef { FIRST_ITEM, SECOND_ITEM } EnumDef;' does not define an enum. I've written hundreds of huge programs and had the mis-fortune to perform maintenance on programs others have written. From the hard hand of experience, using typedef on a struct only leads to problems. Hopefully the programmer is not so handicapped that they have problems typing a full definition when they declare a struct instance. C is not Basic, so typing some more characters is not detrimental to the operation of the program.
– user3629249
May 28 '15 at 20:57
2
For those that feel some abhorrence to typing more than the absolute minimum number of characters, may I suggest joining some group that tries to write applications with the minimum number of keystrokes. Just don't use their new 'skill' in a work environment, especially a work environment that rigorously performs peer reviews
– user3629249
May 28 '15 at 20:59
Note, it is usually discouraged to useenum
as a type, as many compilers emit strange warnings when using them 'wrong'. For example, initializing anenum
to 0 might give an 'integer constant not in enum' warning. Forward-declaring anenum
is also not allowed. One should useint
(orunsigned int
) instead.
– YoYoYonnY
Nov 30 '16 at 21:31
3
That example does not compile , nor would I expect it to. Compiling Debug/test.o test.c:10:17: error: field has incomplete type 'enum EnuumDef' enum EnuumDef MyEnum; ^ test.c:10:8: note: forward declaration of 'enum EnuumDef' enum EnuumDef MyEnum; ^ 1 error generated. gnuc, with std=c99.
– natersoz
Jan 21 '17 at 19:49
|
show 1 more comment
Linux kernel coding style Chapter 5 gives great pros and cons (mostly cons) of using typedef
.
Please don't use things like "vps_t".
It's a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean?
In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
Lots of people think that typedefs "help readability". Not so. They are useful only for:
(a) totally opaque objects (where the typedef is actively used to hide what the object is).
Example: "pte_t" etc. opaque objects that you can only access using the proper accessor functions.
NOTE! Opaqueness and "accessor functions" are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely zero portably accessible information there.
(b) Clear integer types, where the abstraction helps avoid confusion whether it is "int" or "long".
u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.
NOTE! Again - there needs to be a reason for this. If something is "unsigned long", then there's no reason to do
typedef unsigned long myflags_t;
but if there is a clear reason for why it under certain circumstances might be an "unsigned int" and under other configurations might be "unsigned long", then by all means go ahead and use a typedef.
(c) when you use sparse to literally create a new type for type-checking.
(d) New types which are identical to standard C99 types, in certain exceptional circumstances.
Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like 'uint32_t', some people object to their use anyway.
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed equivalents which are identical to standard types are permitted -- although they are not mandatory in new code of your own.
When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.
(e) Types safe for use in userspace.
In certain structures which are visible to userspace, we cannot require C99 types and cannot use the 'u32' form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.
Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
4
'Opaqueness and "accessor functions" are not good in themselves'. Can someone explain why? I would think information hiding and encapsulation would be a very good idea.
– Yawar
Dec 4 '16 at 5:48
5
@Yawar I just read this document and had exactly the same thought. Sure, C isn't object orientated, but abstraction is still a thing.
– Baldrickk
Jan 10 '17 at 16:18
add a comment |
I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.
Style:
Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.
Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.
Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.
9
Clean would be not repeatingstruct
everywhere... Typedef's make new types. What do you use? Types. We don't care if it's a struct, union, or enum, that's why we typedef it.
– GManNickG
May 29 '10 at 7:14
10
No, we do care if it's a struct or union, versus an enum or some atomic type. You can't coerce a struct to an integer or to a pointer (or to any other type, for that matter), which is all you sometimes have to store some context. Having the 'struct' or 'union' keywords around improves locality of reasoning. Nobody says you need to know what's inside the struct.
– Bernd Jendrissek
Nov 26 '12 at 3:59
1
@BerndJendrissek: Structs and unions are different from other types, but should client code care about which of those two things (struct or union) something like aFILE
is?
– supercat
Mar 27 '15 at 18:54
3
@supercat FILE is a good use of typedef. I think that typedef is overused, not that it's a misfeature of the language. IMHO using typedef for everything is the "speculative overgenerality" code smell. Notice that you declare variables as FILE *foo, never as FILE foo. To me, this matters.
– Bernd Jendrissek
Mar 29 '15 at 17:16
1
@supercat: "If file-identifying variables were of type FILE rather than FILE* ..." But that's exactly the ambiguity that typedefs enable! We're just used to fopen taking a FILE * so we don't fret about it, but each time you add typedef you're introducing yet another bit of cognitive overhead: does this API want foo_t args or foo_t *? Explicitly carrying the 'struct' along improves locality of reasoning, if at the cost of a few more characters per function definition.
– Bernd Jendrissek
Mar 30 '15 at 18:47
|
show 4 more comments
It turns out that there are pros and cons. A useful source of information is the seminal book "Expert C Programming" (Chapter 3). Briefly, in C you have multiple namespaces: tags, types, member names and identifiers. typedef
introduces an alias for a type and locates it in the tag namespace. Namely,
typedef struct Tag{
...members...
}Type;
defines two things. One Tag in the tag namespace and one Type in the type namespace. So you can do both Type myType
and struct Tag myTagType
. Declarations like struct Type myType
or Tag myTagType
are illegal. In addition, in a declaration like this:
typedef Type *Type_ptr;
we define a pointer to our Type. So if we declare:
Type_ptr var1, var2;
struct Tag *myTagType1, myTagType2;
then var1
,var2
and myTagType1
are pointers to Type but myTagType2
not.
In the above-mentioned book, it mentions that typedefing structs are not very useful as it only saves the programmer from writing the word struct. However, I have an objection, like many other C programmers. Although it sometimes turns to obfuscate some names (that's why it is not advisable in large code bases like the kernel) when you want to implement polymorphism in C it helps a lot look here for details. Example:
typedef struct MyWriter_t{
MyPipe super;
MyQueue relative;
uint32_t flags;
...
}MyWriter;
you can do:
void my_writer_func(MyPipe *s)
{
MyWriter *self = (MyWriter *) s;
uint32_t myFlags = self->flags;
...
}
So you can access an outer member (flags
) by the inner struct (MyPipe
) through casting. For me it is less confusing to cast the whole type than doing (struct MyWriter_ *) s;
every time you want to perform such functionality. In these cases brief referencing is a big deal especially if you heavily employ the technique in your code.
Finally, the last aspect with typedef
ed types is the inability to extend them, in contrast to macros. If for example, you have:
#define X char[10] or
typedef char Y[10]
you can then declare
unsigned X x; but not
unsigned Y y;
We do not really care for this for structs because it does not apply to storage specifiers (volatile
and const
).
1
MyPipe *s; MyWriter *self = (MyWriter *) s;
and you've just broken strict aliasing.
– Jonathon Reinhart
Jun 1 '15 at 19:18
@JonathonReinhart It would be illustrative to mention how this can be avoided, for example how the hugely cast-happy GTK+ works around it: bugzilla.gnome.org/show_bug.cgi?id=140722 / mail.gnome.org/archives/gtk-devel-list/2004-April/msg00196.html
– underscore_d
Apr 9 '16 at 16:35
"typedef introduces an alias for a type and locates it in the tag namespace. Namely"typedef struct Tag{ ...members... }Type;
"defines two things" doesn't quite make sense. if typedef defines tags then 'Type' here should also be a tag. The truth is the definition defines 2 tags and 1 type (or 2 types and 1 tag. not sure):struct Tag
,Tag
andType
.struct Tag
is definitely a type.Tag
is a tag. but the confusion is whetherType
is a tag or a type
– Qwertyzw
May 11 '18 at 13:39
add a comment |
Let's start with the basics and work our way up.
Here is an example of Structure definition:
struct point
{
int x, y;
};
Here the name point
is optional.
A Structure can be declared during its definition or after.
Declaring during definition
struct point
{
int x, y;
} first_point, second_point;
Declaring after definition
struct point
{
int x, y;
};
struct point first_point, second_point;
Now, carefully note the last case above; you need to write struct point
to declare Structures of that type if you decide to create that type at a later point in your code.
Enter typedef
. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using typedef
during its definition might be a good idea since you can save some typing moving forward.
typedef struct point
{
int x, y;
} Points;
Points first_point, second_point;
A word of caution while naming your custom type
Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.
add a comment |
the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.
GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:
struct MyStruct
{
int i;
};
// The following is legal in C++:
MyStruct obj;
obj.i = 7;
add a comment |
typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
Of course you can always add:
typedef struct foo foo_t;
typedef struct bar bar_t;
What exactly is the point of that?
add a comment |
A>
a typdef aids in the meaning and documentation of a program by allowing creation of more meaningful synonyms for data types. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).
B>
a structure defines a type. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit
C>
typedef'ing a struct is explained in A above.
D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames.
add a comment |
Turns out in C99 typedef is required. It is outdated, but a lot of tools (ala HackRank) use c99 as its pure C implementation. And typedef is required there.
I'm not saying they should change (maybe have two C options) if the requirement changed, those of us studing for interviews on the site would be SOL.
2
"Turns out in C99typedef
is required." What do you mean?
– Julien Lopez
Nov 2 '16 at 9:54
The question is aboutC
, notC++
. InC
typedefs are 'required' (and will most likely always be). 'Required' as in, you will not be able to declare a variablePoint varName;
and have the type be synonymous withstruct Point;
without atypedef struct Point Point;
.
– YoYoYonnY
Nov 30 '16 at 21:26
add a comment |
In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'.
In 'C' we often declare a 'struct' outside of the 'main' function. For example:
struct complex{ int real_part, img_part }COMPLEX;
main(){
struct KOMPLEKS number; // number type is now a struct type
number.real_part = 3;
number.img_part = -1;
printf("Number: %d.%d i n",number.real_part, number.img_part);
}
Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:
typedef struct complex{int real_part, img_part; }COMPLEX;
//now COMPLEX is the new name for this structure and if I want to use it without
// a keyword like in the first example 'struct complex number'.
main(){
COMPLEX number; // number is now the same type as in the first example
number.real_part = 1;
number.img)part = 5;
printf("%d %d n", number.real_part, number.img_part);
}
If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'.
add a comment |
At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat "#include" and other)
so :
struct a
{
int i;
};
struct b
{
struct a;
int i;
int j;
};
struct b is expended as something like this :
struct b
{
struct a
{
int i;
};
int i;
int j;
}
and so, at compile time it evolve on stack as something like:
b:
int ai
int i
int j
that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.
typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :
typedef struct a A; //anticipated declaration for member declaration
typedef struct a //Implemented declaration
{
A* b; // member declaration
}A;
is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions.
This mean that in C typedefs are more near as C++ class than lonely structs.
3
It isn't difficult to have self-referential structs at all. struct foo { struct foo *next; int thing; }
– Bernd Jendrissek
Mar 30 '15 at 18:52
4
...what? Saying preprocessor to describe the resolution ofstructs
andtypedef
s is bad enough, but the rest of your writing is so confusing that I find it hard to get any message from it. One thing I can say, though, is that your idea that a non-typedef
dstruct
cannot be forward-declared or used as an opaque (pointer) member is totally false. In your 1st example,struct b
can trivially contain astruct a *
, notypedef
required. The assertions thatstruct
s are merely dumb pieces of macro-expansion, and thattypedef
s give them revolutionary new powers, are painfully incorrect
– underscore_d
Apr 9 '16 at 16:44
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f252780%2fwhy-should-we-typedef-a-struct-so-often-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
As Greg Hewgill said, the typedef means you no longer have to write struct
all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef
, is the case I guess.
Also note that while your example (and mine) omitted naming the struct
itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
typedef struct Point Point;
Point * point_new(int x, int y);
and then provide the struct
definition in the implementation file:
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of typedef
to hide struct
is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
53
You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).
– dreamlax
Jan 6 '11 at 10:40
11
@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.
– brianmearns
Jan 16 '12 at 17:08
9
It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.
– William Pursell
Jan 25 '12 at 14:15
7
@Rerito fyi, page 166 of C99 draft, All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use. And All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
– Ring Ø
Apr 15 '13 at 4:41
9
Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle
– gsingh2011
May 29 '13 at 0:13
|
show 20 more comments
As Greg Hewgill said, the typedef means you no longer have to write struct
all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef
, is the case I guess.
Also note that while your example (and mine) omitted naming the struct
itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
typedef struct Point Point;
Point * point_new(int x, int y);
and then provide the struct
definition in the implementation file:
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of typedef
to hide struct
is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
53
You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).
– dreamlax
Jan 6 '11 at 10:40
11
@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.
– brianmearns
Jan 16 '12 at 17:08
9
It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.
– William Pursell
Jan 25 '12 at 14:15
7
@Rerito fyi, page 166 of C99 draft, All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use. And All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
– Ring Ø
Apr 15 '13 at 4:41
9
Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle
– gsingh2011
May 29 '13 at 0:13
|
show 20 more comments
As Greg Hewgill said, the typedef means you no longer have to write struct
all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef
, is the case I guess.
Also note that while your example (and mine) omitted naming the struct
itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
typedef struct Point Point;
Point * point_new(int x, int y);
and then provide the struct
definition in the implementation file:
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of typedef
to hide struct
is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
As Greg Hewgill said, the typedef means you no longer have to write struct
all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef
, is the case I guess.
Also note that while your example (and mine) omitted naming the struct
itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
typedef struct Point Point;
Point * point_new(int x, int y);
and then provide the struct
definition in the implementation file:
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of typedef
to hide struct
is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
edited Nov 23 '18 at 12:59
ratchet freak
40.9k44493
40.9k44493
answered Oct 31 '08 at 7:37
unwindunwind
324k52398529
324k52398529
53
You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).
– dreamlax
Jan 6 '11 at 10:40
11
@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.
– brianmearns
Jan 16 '12 at 17:08
9
It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.
– William Pursell
Jan 25 '12 at 14:15
7
@Rerito fyi, page 166 of C99 draft, All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use. And All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
– Ring Ø
Apr 15 '13 at 4:41
9
Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle
– gsingh2011
May 29 '13 at 0:13
|
show 20 more comments
53
You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).
– dreamlax
Jan 6 '11 at 10:40
11
@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.
– brianmearns
Jan 16 '12 at 17:08
9
It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.
– William Pursell
Jan 25 '12 at 14:15
7
@Rerito fyi, page 166 of C99 draft, All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use. And All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
– Ring Ø
Apr 15 '13 at 4:41
9
Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle
– gsingh2011
May 29 '13 at 0:13
53
53
You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).
– dreamlax
Jan 6 '11 at 10:40
You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).
– dreamlax
Jan 6 '11 at 10:40
11
11
@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.
– brianmearns
Jan 16 '12 at 17:08
@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.
– brianmearns
Jan 16 '12 at 17:08
9
9
It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.
– William Pursell
Jan 25 '12 at 14:15
It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.
– William Pursell
Jan 25 '12 at 14:15
7
7
@Rerito fyi, page 166 of C99 draft, All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use. And All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
– Ring Ø
Apr 15 '13 at 4:41
@Rerito fyi, page 166 of C99 draft, All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use. And All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
– Ring Ø
Apr 15 '13 at 4:41
9
9
Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle
– gsingh2011
May 29 '13 at 0:13
Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle
– gsingh2011
May 29 '13 at 0:13
|
show 20 more comments
It's amazing how many people get this wrong. 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.
Consider:
#ifndef FOO_H
#define FOO_H 1
#define FOO_DEF (0xDEADBABE)
struct bar; /* forward declaration, defined in bar.h*/
struct foo {
struct bar *bar;
};
#endif
With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF
definition. If it doesn't attempt to dereference the 'bar' member of the foo
struct then there will be no need to include the "bar.h" file.
Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:
struct foo *foo;
printf("foo->bar = %p", foo->bar);
Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.
If I have to maintain your code, I will remove your typedef'd structs.
32
What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
– William Pursell
Jan 25 '12 at 14:04
27
Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.
– Jens
Mar 14 '12 at 10:31
30
The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle
– jasso
Dec 9 '12 at 22:39
55
What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to usetypedef struct X { ... } X
. That way you can use the short formX
to address the struct anywhere the definition is available, but can still forward-declare and usestruct X
when desired.
– Pavel Minaev
Mar 20 '13 at 7:18
6
I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.
– Nathan Day
Jun 1 '13 at 10:26
|
show 7 more comments
It's amazing how many people get this wrong. 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.
Consider:
#ifndef FOO_H
#define FOO_H 1
#define FOO_DEF (0xDEADBABE)
struct bar; /* forward declaration, defined in bar.h*/
struct foo {
struct bar *bar;
};
#endif
With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF
definition. If it doesn't attempt to dereference the 'bar' member of the foo
struct then there will be no need to include the "bar.h" file.
Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:
struct foo *foo;
printf("foo->bar = %p", foo->bar);
Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.
If I have to maintain your code, I will remove your typedef'd structs.
32
What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
– William Pursell
Jan 25 '12 at 14:04
27
Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.
– Jens
Mar 14 '12 at 10:31
30
The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle
– jasso
Dec 9 '12 at 22:39
55
What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to usetypedef struct X { ... } X
. That way you can use the short formX
to address the struct anywhere the definition is available, but can still forward-declare and usestruct X
when desired.
– Pavel Minaev
Mar 20 '13 at 7:18
6
I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.
– Nathan Day
Jun 1 '13 at 10:26
|
show 7 more comments
It's amazing how many people get this wrong. 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.
Consider:
#ifndef FOO_H
#define FOO_H 1
#define FOO_DEF (0xDEADBABE)
struct bar; /* forward declaration, defined in bar.h*/
struct foo {
struct bar *bar;
};
#endif
With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF
definition. If it doesn't attempt to dereference the 'bar' member of the foo
struct then there will be no need to include the "bar.h" file.
Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:
struct foo *foo;
printf("foo->bar = %p", foo->bar);
Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.
If I have to maintain your code, I will remove your typedef'd structs.
It's amazing how many people get this wrong. 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.
Consider:
#ifndef FOO_H
#define FOO_H 1
#define FOO_DEF (0xDEADBABE)
struct bar; /* forward declaration, defined in bar.h*/
struct foo {
struct bar *bar;
};
#endif
With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF
definition. If it doesn't attempt to dereference the 'bar' member of the foo
struct then there will be no need to include the "bar.h" file.
Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:
struct foo *foo;
printf("foo->bar = %p", foo->bar);
Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.
If I have to maintain your code, I will remove your typedef'd structs.
edited Nov 28 '14 at 23:32
Jens
51k1489132
51k1489132
answered Dec 30 '10 at 21:20
Jerry HicksJerry Hicks
2,2561105
2,2561105
32
What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
– William Pursell
Jan 25 '12 at 14:04
27
Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.
– Jens
Mar 14 '12 at 10:31
30
The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle
– jasso
Dec 9 '12 at 22:39
55
What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to usetypedef struct X { ... } X
. That way you can use the short formX
to address the struct anywhere the definition is available, but can still forward-declare and usestruct X
when desired.
– Pavel Minaev
Mar 20 '13 at 7:18
6
I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.
– Nathan Day
Jun 1 '13 at 10:26
|
show 7 more comments
32
What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
– William Pursell
Jan 25 '12 at 14:04
27
Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.
– Jens
Mar 14 '12 at 10:31
30
The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle
– jasso
Dec 9 '12 at 22:39
55
What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to usetypedef struct X { ... } X
. That way you can use the short formX
to address the struct anywhere the definition is available, but can still forward-declare and usestruct X
when desired.
– Pavel Minaev
Mar 20 '13 at 7:18
6
I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.
– Nathan Day
Jun 1 '13 at 10:26
32
32
What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
– William Pursell
Jan 25 '12 at 14:04
What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
– William Pursell
Jan 25 '12 at 14:04
27
27
Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.
– Jens
Mar 14 '12 at 10:31
Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.
– Jens
Mar 14 '12 at 10:31
30
30
The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle
– jasso
Dec 9 '12 at 22:39
The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle
– jasso
Dec 9 '12 at 22:39
55
55
What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to use
typedef struct X { ... } X
. That way you can use the short form X
to address the struct anywhere the definition is available, but can still forward-declare and use struct X
when desired.– Pavel Minaev
Mar 20 '13 at 7:18
What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to use
typedef struct X { ... } X
. That way you can use the short form X
to address the struct anywhere the definition is available, but can still forward-declare and use struct X
when desired.– Pavel Minaev
Mar 20 '13 at 7:18
6
6
I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.
– Nathan Day
Jun 1 '13 at 10:26
I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.
– Nathan Day
Jun 1 '13 at 10:26
|
show 7 more comments
From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):
The C language rules for naming
structs are a little eccentric, but
they're pretty harmless. However, when
extended to classes in C++, those same
rules open little cracks for bugs to
crawl through.
In C, the name s appearing in
struct s
{
...
};
is a tag. A tag name is not a type
name. Given the definition above,
declarations such as
s x; /* error in C */
s *p; /* error in C */
are errors in C. You must write them
as
struct s x; /* OK */
struct s *p; /* OK */
The names of unions and enumerations
are also tags rather than types.
In C, tags are distinct from all other
names (for functions, types,
variables, and enumeration constants).
C compilers maintain tags in a symbol
table that's conceptually if not
physically separate from the table
that holds all other names. Thus, it
is possible for a C program to have
both a tag and an another name with
the same spelling in the same scope.
For example,
struct s s;
is a valid declaration which declares
variable s of type struct s. It may
not be good practice, but C compilers
must accept it. I have never seen a
rationale for why C was designed this
way. I have always thought it was a
mistake, but there it is.
Many programmers (including yours
truly) prefer to think of struct names
as type names, so they define an alias
for the tag using a typedef. For
example, defining
struct s
{
...
};
typedef struct s S;
lets you use S in place of struct s,
as in
S x;
S *p;
A program cannot use S as the name of
both a type and a variable (or
function or enumeration constant):
S S; // error
This is good.
The tag name in a struct, union, or
enum definition is optional. Many
programmers fold the struct definition
into the typedef and dispense with the
tag altogether, as in:
typedef struct
{
...
} S;
The linked article also has a discussion about how the C++ behavior of not requireing a typedef
can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef
your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef
the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.
4
Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.
– user2061057
Mar 3 '16 at 15:19
2
One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with theint stat(const char *restrict path, struct stat *restrict buf)
function. There you have a functionstat
in the ordinary name space andstruct stat
in the tag name space.
– Jonathan Leffler
Jun 5 '16 at 22:02
1
your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check
– eRaisedToX
Aug 3 '16 at 7:24
"declarations such as .. are errors in C" Why? It isn't in C++ or C#. Why is C designed this way?
– Aaron Franke
Nov 16 '18 at 7:00
add a comment |
From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):
The C language rules for naming
structs are a little eccentric, but
they're pretty harmless. However, when
extended to classes in C++, those same
rules open little cracks for bugs to
crawl through.
In C, the name s appearing in
struct s
{
...
};
is a tag. A tag name is not a type
name. Given the definition above,
declarations such as
s x; /* error in C */
s *p; /* error in C */
are errors in C. You must write them
as
struct s x; /* OK */
struct s *p; /* OK */
The names of unions and enumerations
are also tags rather than types.
In C, tags are distinct from all other
names (for functions, types,
variables, and enumeration constants).
C compilers maintain tags in a symbol
table that's conceptually if not
physically separate from the table
that holds all other names. Thus, it
is possible for a C program to have
both a tag and an another name with
the same spelling in the same scope.
For example,
struct s s;
is a valid declaration which declares
variable s of type struct s. It may
not be good practice, but C compilers
must accept it. I have never seen a
rationale for why C was designed this
way. I have always thought it was a
mistake, but there it is.
Many programmers (including yours
truly) prefer to think of struct names
as type names, so they define an alias
for the tag using a typedef. For
example, defining
struct s
{
...
};
typedef struct s S;
lets you use S in place of struct s,
as in
S x;
S *p;
A program cannot use S as the name of
both a type and a variable (or
function or enumeration constant):
S S; // error
This is good.
The tag name in a struct, union, or
enum definition is optional. Many
programmers fold the struct definition
into the typedef and dispense with the
tag altogether, as in:
typedef struct
{
...
} S;
The linked article also has a discussion about how the C++ behavior of not requireing a typedef
can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef
your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef
the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.
4
Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.
– user2061057
Mar 3 '16 at 15:19
2
One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with theint stat(const char *restrict path, struct stat *restrict buf)
function. There you have a functionstat
in the ordinary name space andstruct stat
in the tag name space.
– Jonathan Leffler
Jun 5 '16 at 22:02
1
your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check
– eRaisedToX
Aug 3 '16 at 7:24
"declarations such as .. are errors in C" Why? It isn't in C++ or C#. Why is C designed this way?
– Aaron Franke
Nov 16 '18 at 7:00
add a comment |
From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):
The C language rules for naming
structs are a little eccentric, but
they're pretty harmless. However, when
extended to classes in C++, those same
rules open little cracks for bugs to
crawl through.
In C, the name s appearing in
struct s
{
...
};
is a tag. A tag name is not a type
name. Given the definition above,
declarations such as
s x; /* error in C */
s *p; /* error in C */
are errors in C. You must write them
as
struct s x; /* OK */
struct s *p; /* OK */
The names of unions and enumerations
are also tags rather than types.
In C, tags are distinct from all other
names (for functions, types,
variables, and enumeration constants).
C compilers maintain tags in a symbol
table that's conceptually if not
physically separate from the table
that holds all other names. Thus, it
is possible for a C program to have
both a tag and an another name with
the same spelling in the same scope.
For example,
struct s s;
is a valid declaration which declares
variable s of type struct s. It may
not be good practice, but C compilers
must accept it. I have never seen a
rationale for why C was designed this
way. I have always thought it was a
mistake, but there it is.
Many programmers (including yours
truly) prefer to think of struct names
as type names, so they define an alias
for the tag using a typedef. For
example, defining
struct s
{
...
};
typedef struct s S;
lets you use S in place of struct s,
as in
S x;
S *p;
A program cannot use S as the name of
both a type and a variable (or
function or enumeration constant):
S S; // error
This is good.
The tag name in a struct, union, or
enum definition is optional. Many
programmers fold the struct definition
into the typedef and dispense with the
tag altogether, as in:
typedef struct
{
...
} S;
The linked article also has a discussion about how the C++ behavior of not requireing a typedef
can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef
your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef
the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.
From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):
The C language rules for naming
structs are a little eccentric, but
they're pretty harmless. However, when
extended to classes in C++, those same
rules open little cracks for bugs to
crawl through.
In C, the name s appearing in
struct s
{
...
};
is a tag. A tag name is not a type
name. Given the definition above,
declarations such as
s x; /* error in C */
s *p; /* error in C */
are errors in C. You must write them
as
struct s x; /* OK */
struct s *p; /* OK */
The names of unions and enumerations
are also tags rather than types.
In C, tags are distinct from all other
names (for functions, types,
variables, and enumeration constants).
C compilers maintain tags in a symbol
table that's conceptually if not
physically separate from the table
that holds all other names. Thus, it
is possible for a C program to have
both a tag and an another name with
the same spelling in the same scope.
For example,
struct s s;
is a valid declaration which declares
variable s of type struct s. It may
not be good practice, but C compilers
must accept it. I have never seen a
rationale for why C was designed this
way. I have always thought it was a
mistake, but there it is.
Many programmers (including yours
truly) prefer to think of struct names
as type names, so they define an alias
for the tag using a typedef. For
example, defining
struct s
{
...
};
typedef struct s S;
lets you use S in place of struct s,
as in
S x;
S *p;
A program cannot use S as the name of
both a type and a variable (or
function or enumeration constant):
S S; // error
This is good.
The tag name in a struct, union, or
enum definition is optional. Many
programmers fold the struct definition
into the typedef and dispense with the
tag altogether, as in:
typedef struct
{
...
} S;
The linked article also has a discussion about how the C++ behavior of not requireing a typedef
can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef
your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef
the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.
edited Dec 9 '16 at 20:09
community wiki
2 revs, 2 users 99%
Michael Burr
4
Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.
– user2061057
Mar 3 '16 at 15:19
2
One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with theint stat(const char *restrict path, struct stat *restrict buf)
function. There you have a functionstat
in the ordinary name space andstruct stat
in the tag name space.
– Jonathan Leffler
Jun 5 '16 at 22:02
1
your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check
– eRaisedToX
Aug 3 '16 at 7:24
"declarations such as .. are errors in C" Why? It isn't in C++ or C#. Why is C designed this way?
– Aaron Franke
Nov 16 '18 at 7:00
add a comment |
4
Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.
– user2061057
Mar 3 '16 at 15:19
2
One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with theint stat(const char *restrict path, struct stat *restrict buf)
function. There you have a functionstat
in the ordinary name space andstruct stat
in the tag name space.
– Jonathan Leffler
Jun 5 '16 at 22:02
1
your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check
– eRaisedToX
Aug 3 '16 at 7:24
"declarations such as .. are errors in C" Why? It isn't in C++ or C#. Why is C designed this way?
– Aaron Franke
Nov 16 '18 at 7:00
4
4
Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.
– user2061057
Mar 3 '16 at 15:19
Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.
– user2061057
Mar 3 '16 at 15:19
2
2
One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with the
int stat(const char *restrict path, struct stat *restrict buf)
function. There you have a function stat
in the ordinary name space and struct stat
in the tag name space.– Jonathan Leffler
Jun 5 '16 at 22:02
One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with the
int stat(const char *restrict path, struct stat *restrict buf)
function. There you have a function stat
in the ordinary name space and struct stat
in the tag name space.– Jonathan Leffler
Jun 5 '16 at 22:02
1
1
your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check
– eRaisedToX
Aug 3 '16 at 7:24
your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check
– eRaisedToX
Aug 3 '16 at 7:24
"declarations such as .. are errors in C" Why? It isn't in C++ or C#. Why is C designed this way?
– Aaron Franke
Nov 16 '18 at 7:00
"declarations such as .. are errors in C" Why? It isn't in C++ or C#. Why is C designed this way?
– Aaron Franke
Nov 16 '18 at 7:00
add a comment |
Using a typedef
avoids having to write struct
every time you declare a variable of that type:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
1
ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?
– Manoj Doubts
Oct 31 '08 at 12:03
4
Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.
– Michael Carman
Oct 31 '08 at 13:05
37
It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.
– Herms
Oct 31 '08 at 19:36
3
unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.
– user3629249
May 28 '15 at 20:50
add a comment |
Using a typedef
avoids having to write struct
every time you declare a variable of that type:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
1
ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?
– Manoj Doubts
Oct 31 '08 at 12:03
4
Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.
– Michael Carman
Oct 31 '08 at 13:05
37
It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.
– Herms
Oct 31 '08 at 19:36
3
unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.
– user3629249
May 28 '15 at 20:50
add a comment |
Using a typedef
avoids having to write struct
every time you declare a variable of that type:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
Using a typedef
avoids having to write struct
every time you declare a variable of that type:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
answered Oct 31 '08 at 7:16
Greg HewgillGreg Hewgill
681k14710221175
681k14710221175
1
ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?
– Manoj Doubts
Oct 31 '08 at 12:03
4
Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.
– Michael Carman
Oct 31 '08 at 13:05
37
It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.
– Herms
Oct 31 '08 at 19:36
3
unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.
– user3629249
May 28 '15 at 20:50
add a comment |
1
ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?
– Manoj Doubts
Oct 31 '08 at 12:03
4
Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.
– Michael Carman
Oct 31 '08 at 13:05
37
It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.
– Herms
Oct 31 '08 at 19:36
3
unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.
– user3629249
May 28 '15 at 20:50
1
1
ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?
– Manoj Doubts
Oct 31 '08 at 12:03
ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?
– Manoj Doubts
Oct 31 '08 at 12:03
4
4
Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.
– Michael Carman
Oct 31 '08 at 13:05
Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.
– Michael Carman
Oct 31 '08 at 13:05
37
37
It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.
– Herms
Oct 31 '08 at 19:36
It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.
– Herms
Oct 31 '08 at 19:36
3
3
unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.
– user3629249
May 28 '15 at 20:50
unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.
– user3629249
May 28 '15 at 20:50
add a comment |
One other good reason to always typedef enums and structs results from this problem:
enum EnumDef
{
FIRST_ITEM,
SECOND_ITEM
};
struct StructDef
{
enum EnuumDef MyEnum;
unsigned int MyVar;
} MyStruct;
Notice the typo in EnumDef in the struct (EnuumDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.
With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:
typedef
{
FIRST_ITEM,
SECOND_ITEM
} EnumDef;
typedef struct
{
EnuumDef MyEnum; /* compiler error (unknown type) */
unsigned int MyVar;
} StructDef;
StrructDef MyStruct; /* compiler error (unknown type) */
I would advocate ALWAYS typedef'ing structs and enumerations.
Not only to save some typing (no pun intended ;)), but because it is safer.
Even worse, your typo might coincide with a different tag. In the case of a struct this could result in the entire program compiling correctly and having runtime undefined behaviour.
– M.M
Feb 14 '15 at 22:15
3
this definition: 'typedef { FIRST_ITEM, SECOND_ITEM } EnumDef;' does not define an enum. I've written hundreds of huge programs and had the mis-fortune to perform maintenance on programs others have written. From the hard hand of experience, using typedef on a struct only leads to problems. Hopefully the programmer is not so handicapped that they have problems typing a full definition when they declare a struct instance. C is not Basic, so typing some more characters is not detrimental to the operation of the program.
– user3629249
May 28 '15 at 20:57
2
For those that feel some abhorrence to typing more than the absolute minimum number of characters, may I suggest joining some group that tries to write applications with the minimum number of keystrokes. Just don't use their new 'skill' in a work environment, especially a work environment that rigorously performs peer reviews
– user3629249
May 28 '15 at 20:59
Note, it is usually discouraged to useenum
as a type, as many compilers emit strange warnings when using them 'wrong'. For example, initializing anenum
to 0 might give an 'integer constant not in enum' warning. Forward-declaring anenum
is also not allowed. One should useint
(orunsigned int
) instead.
– YoYoYonnY
Nov 30 '16 at 21:31
3
That example does not compile , nor would I expect it to. Compiling Debug/test.o test.c:10:17: error: field has incomplete type 'enum EnuumDef' enum EnuumDef MyEnum; ^ test.c:10:8: note: forward declaration of 'enum EnuumDef' enum EnuumDef MyEnum; ^ 1 error generated. gnuc, with std=c99.
– natersoz
Jan 21 '17 at 19:49
|
show 1 more comment
One other good reason to always typedef enums and structs results from this problem:
enum EnumDef
{
FIRST_ITEM,
SECOND_ITEM
};
struct StructDef
{
enum EnuumDef MyEnum;
unsigned int MyVar;
} MyStruct;
Notice the typo in EnumDef in the struct (EnuumDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.
With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:
typedef
{
FIRST_ITEM,
SECOND_ITEM
} EnumDef;
typedef struct
{
EnuumDef MyEnum; /* compiler error (unknown type) */
unsigned int MyVar;
} StructDef;
StrructDef MyStruct; /* compiler error (unknown type) */
I would advocate ALWAYS typedef'ing structs and enumerations.
Not only to save some typing (no pun intended ;)), but because it is safer.
Even worse, your typo might coincide with a different tag. In the case of a struct this could result in the entire program compiling correctly and having runtime undefined behaviour.
– M.M
Feb 14 '15 at 22:15
3
this definition: 'typedef { FIRST_ITEM, SECOND_ITEM } EnumDef;' does not define an enum. I've written hundreds of huge programs and had the mis-fortune to perform maintenance on programs others have written. From the hard hand of experience, using typedef on a struct only leads to problems. Hopefully the programmer is not so handicapped that they have problems typing a full definition when they declare a struct instance. C is not Basic, so typing some more characters is not detrimental to the operation of the program.
– user3629249
May 28 '15 at 20:57
2
For those that feel some abhorrence to typing more than the absolute minimum number of characters, may I suggest joining some group that tries to write applications with the minimum number of keystrokes. Just don't use their new 'skill' in a work environment, especially a work environment that rigorously performs peer reviews
– user3629249
May 28 '15 at 20:59
Note, it is usually discouraged to useenum
as a type, as many compilers emit strange warnings when using them 'wrong'. For example, initializing anenum
to 0 might give an 'integer constant not in enum' warning. Forward-declaring anenum
is also not allowed. One should useint
(orunsigned int
) instead.
– YoYoYonnY
Nov 30 '16 at 21:31
3
That example does not compile , nor would I expect it to. Compiling Debug/test.o test.c:10:17: error: field has incomplete type 'enum EnuumDef' enum EnuumDef MyEnum; ^ test.c:10:8: note: forward declaration of 'enum EnuumDef' enum EnuumDef MyEnum; ^ 1 error generated. gnuc, with std=c99.
– natersoz
Jan 21 '17 at 19:49
|
show 1 more comment
One other good reason to always typedef enums and structs results from this problem:
enum EnumDef
{
FIRST_ITEM,
SECOND_ITEM
};
struct StructDef
{
enum EnuumDef MyEnum;
unsigned int MyVar;
} MyStruct;
Notice the typo in EnumDef in the struct (EnuumDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.
With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:
typedef
{
FIRST_ITEM,
SECOND_ITEM
} EnumDef;
typedef struct
{
EnuumDef MyEnum; /* compiler error (unknown type) */
unsigned int MyVar;
} StructDef;
StrructDef MyStruct; /* compiler error (unknown type) */
I would advocate ALWAYS typedef'ing structs and enumerations.
Not only to save some typing (no pun intended ;)), but because it is safer.
One other good reason to always typedef enums and structs results from this problem:
enum EnumDef
{
FIRST_ITEM,
SECOND_ITEM
};
struct StructDef
{
enum EnuumDef MyEnum;
unsigned int MyVar;
} MyStruct;
Notice the typo in EnumDef in the struct (EnuumDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.
With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:
typedef
{
FIRST_ITEM,
SECOND_ITEM
} EnumDef;
typedef struct
{
EnuumDef MyEnum; /* compiler error (unknown type) */
unsigned int MyVar;
} StructDef;
StrructDef MyStruct; /* compiler error (unknown type) */
I would advocate ALWAYS typedef'ing structs and enumerations.
Not only to save some typing (no pun intended ;)), but because it is safer.
edited Feb 14 '15 at 22:14
M.M
107k11120244
107k11120244
answered Mar 31 '09 at 0:00
cscholcschol
8,027105476
8,027105476
Even worse, your typo might coincide with a different tag. In the case of a struct this could result in the entire program compiling correctly and having runtime undefined behaviour.
– M.M
Feb 14 '15 at 22:15
3
this definition: 'typedef { FIRST_ITEM, SECOND_ITEM } EnumDef;' does not define an enum. I've written hundreds of huge programs and had the mis-fortune to perform maintenance on programs others have written. From the hard hand of experience, using typedef on a struct only leads to problems. Hopefully the programmer is not so handicapped that they have problems typing a full definition when they declare a struct instance. C is not Basic, so typing some more characters is not detrimental to the operation of the program.
– user3629249
May 28 '15 at 20:57
2
For those that feel some abhorrence to typing more than the absolute minimum number of characters, may I suggest joining some group that tries to write applications with the minimum number of keystrokes. Just don't use their new 'skill' in a work environment, especially a work environment that rigorously performs peer reviews
– user3629249
May 28 '15 at 20:59
Note, it is usually discouraged to useenum
as a type, as many compilers emit strange warnings when using them 'wrong'. For example, initializing anenum
to 0 might give an 'integer constant not in enum' warning. Forward-declaring anenum
is also not allowed. One should useint
(orunsigned int
) instead.
– YoYoYonnY
Nov 30 '16 at 21:31
3
That example does not compile , nor would I expect it to. Compiling Debug/test.o test.c:10:17: error: field has incomplete type 'enum EnuumDef' enum EnuumDef MyEnum; ^ test.c:10:8: note: forward declaration of 'enum EnuumDef' enum EnuumDef MyEnum; ^ 1 error generated. gnuc, with std=c99.
– natersoz
Jan 21 '17 at 19:49
|
show 1 more comment
Even worse, your typo might coincide with a different tag. In the case of a struct this could result in the entire program compiling correctly and having runtime undefined behaviour.
– M.M
Feb 14 '15 at 22:15
3
this definition: 'typedef { FIRST_ITEM, SECOND_ITEM } EnumDef;' does not define an enum. I've written hundreds of huge programs and had the mis-fortune to perform maintenance on programs others have written. From the hard hand of experience, using typedef on a struct only leads to problems. Hopefully the programmer is not so handicapped that they have problems typing a full definition when they declare a struct instance. C is not Basic, so typing some more characters is not detrimental to the operation of the program.
– user3629249
May 28 '15 at 20:57
2
For those that feel some abhorrence to typing more than the absolute minimum number of characters, may I suggest joining some group that tries to write applications with the minimum number of keystrokes. Just don't use their new 'skill' in a work environment, especially a work environment that rigorously performs peer reviews
– user3629249
May 28 '15 at 20:59
Note, it is usually discouraged to useenum
as a type, as many compilers emit strange warnings when using them 'wrong'. For example, initializing anenum
to 0 might give an 'integer constant not in enum' warning. Forward-declaring anenum
is also not allowed. One should useint
(orunsigned int
) instead.
– YoYoYonnY
Nov 30 '16 at 21:31
3
That example does not compile , nor would I expect it to. Compiling Debug/test.o test.c:10:17: error: field has incomplete type 'enum EnuumDef' enum EnuumDef MyEnum; ^ test.c:10:8: note: forward declaration of 'enum EnuumDef' enum EnuumDef MyEnum; ^ 1 error generated. gnuc, with std=c99.
– natersoz
Jan 21 '17 at 19:49
Even worse, your typo might coincide with a different tag. In the case of a struct this could result in the entire program compiling correctly and having runtime undefined behaviour.
– M.M
Feb 14 '15 at 22:15
Even worse, your typo might coincide with a different tag. In the case of a struct this could result in the entire program compiling correctly and having runtime undefined behaviour.
– M.M
Feb 14 '15 at 22:15
3
3
this definition: 'typedef { FIRST_ITEM, SECOND_ITEM } EnumDef;' does not define an enum. I've written hundreds of huge programs and had the mis-fortune to perform maintenance on programs others have written. From the hard hand of experience, using typedef on a struct only leads to problems. Hopefully the programmer is not so handicapped that they have problems typing a full definition when they declare a struct instance. C is not Basic, so typing some more characters is not detrimental to the operation of the program.
– user3629249
May 28 '15 at 20:57
this definition: 'typedef { FIRST_ITEM, SECOND_ITEM } EnumDef;' does not define an enum. I've written hundreds of huge programs and had the mis-fortune to perform maintenance on programs others have written. From the hard hand of experience, using typedef on a struct only leads to problems. Hopefully the programmer is not so handicapped that they have problems typing a full definition when they declare a struct instance. C is not Basic, so typing some more characters is not detrimental to the operation of the program.
– user3629249
May 28 '15 at 20:57
2
2
For those that feel some abhorrence to typing more than the absolute minimum number of characters, may I suggest joining some group that tries to write applications with the minimum number of keystrokes. Just don't use their new 'skill' in a work environment, especially a work environment that rigorously performs peer reviews
– user3629249
May 28 '15 at 20:59
For those that feel some abhorrence to typing more than the absolute minimum number of characters, may I suggest joining some group that tries to write applications with the minimum number of keystrokes. Just don't use their new 'skill' in a work environment, especially a work environment that rigorously performs peer reviews
– user3629249
May 28 '15 at 20:59
Note, it is usually discouraged to use
enum
as a type, as many compilers emit strange warnings when using them 'wrong'. For example, initializing an enum
to 0 might give an 'integer constant not in enum' warning. Forward-declaring an enum
is also not allowed. One should use int
(or unsigned int
) instead.– YoYoYonnY
Nov 30 '16 at 21:31
Note, it is usually discouraged to use
enum
as a type, as many compilers emit strange warnings when using them 'wrong'. For example, initializing an enum
to 0 might give an 'integer constant not in enum' warning. Forward-declaring an enum
is also not allowed. One should use int
(or unsigned int
) instead.– YoYoYonnY
Nov 30 '16 at 21:31
3
3
That example does not compile , nor would I expect it to. Compiling Debug/test.o test.c:10:17: error: field has incomplete type 'enum EnuumDef' enum EnuumDef MyEnum; ^ test.c:10:8: note: forward declaration of 'enum EnuumDef' enum EnuumDef MyEnum; ^ 1 error generated. gnuc, with std=c99.
– natersoz
Jan 21 '17 at 19:49
That example does not compile , nor would I expect it to. Compiling Debug/test.o test.c:10:17: error: field has incomplete type 'enum EnuumDef' enum EnuumDef MyEnum; ^ test.c:10:8: note: forward declaration of 'enum EnuumDef' enum EnuumDef MyEnum; ^ 1 error generated. gnuc, with std=c99.
– natersoz
Jan 21 '17 at 19:49
|
show 1 more comment
Linux kernel coding style Chapter 5 gives great pros and cons (mostly cons) of using typedef
.
Please don't use things like "vps_t".
It's a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean?
In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
Lots of people think that typedefs "help readability". Not so. They are useful only for:
(a) totally opaque objects (where the typedef is actively used to hide what the object is).
Example: "pte_t" etc. opaque objects that you can only access using the proper accessor functions.
NOTE! Opaqueness and "accessor functions" are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely zero portably accessible information there.
(b) Clear integer types, where the abstraction helps avoid confusion whether it is "int" or "long".
u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.
NOTE! Again - there needs to be a reason for this. If something is "unsigned long", then there's no reason to do
typedef unsigned long myflags_t;
but if there is a clear reason for why it under certain circumstances might be an "unsigned int" and under other configurations might be "unsigned long", then by all means go ahead and use a typedef.
(c) when you use sparse to literally create a new type for type-checking.
(d) New types which are identical to standard C99 types, in certain exceptional circumstances.
Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like 'uint32_t', some people object to their use anyway.
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed equivalents which are identical to standard types are permitted -- although they are not mandatory in new code of your own.
When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.
(e) Types safe for use in userspace.
In certain structures which are visible to userspace, we cannot require C99 types and cannot use the 'u32' form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.
Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
4
'Opaqueness and "accessor functions" are not good in themselves'. Can someone explain why? I would think information hiding and encapsulation would be a very good idea.
– Yawar
Dec 4 '16 at 5:48
5
@Yawar I just read this document and had exactly the same thought. Sure, C isn't object orientated, but abstraction is still a thing.
– Baldrickk
Jan 10 '17 at 16:18
add a comment |
Linux kernel coding style Chapter 5 gives great pros and cons (mostly cons) of using typedef
.
Please don't use things like "vps_t".
It's a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean?
In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
Lots of people think that typedefs "help readability". Not so. They are useful only for:
(a) totally opaque objects (where the typedef is actively used to hide what the object is).
Example: "pte_t" etc. opaque objects that you can only access using the proper accessor functions.
NOTE! Opaqueness and "accessor functions" are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely zero portably accessible information there.
(b) Clear integer types, where the abstraction helps avoid confusion whether it is "int" or "long".
u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.
NOTE! Again - there needs to be a reason for this. If something is "unsigned long", then there's no reason to do
typedef unsigned long myflags_t;
but if there is a clear reason for why it under certain circumstances might be an "unsigned int" and under other configurations might be "unsigned long", then by all means go ahead and use a typedef.
(c) when you use sparse to literally create a new type for type-checking.
(d) New types which are identical to standard C99 types, in certain exceptional circumstances.
Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like 'uint32_t', some people object to their use anyway.
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed equivalents which are identical to standard types are permitted -- although they are not mandatory in new code of your own.
When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.
(e) Types safe for use in userspace.
In certain structures which are visible to userspace, we cannot require C99 types and cannot use the 'u32' form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.
Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
4
'Opaqueness and "accessor functions" are not good in themselves'. Can someone explain why? I would think information hiding and encapsulation would be a very good idea.
– Yawar
Dec 4 '16 at 5:48
5
@Yawar I just read this document and had exactly the same thought. Sure, C isn't object orientated, but abstraction is still a thing.
– Baldrickk
Jan 10 '17 at 16:18
add a comment |
Linux kernel coding style Chapter 5 gives great pros and cons (mostly cons) of using typedef
.
Please don't use things like "vps_t".
It's a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean?
In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
Lots of people think that typedefs "help readability". Not so. They are useful only for:
(a) totally opaque objects (where the typedef is actively used to hide what the object is).
Example: "pte_t" etc. opaque objects that you can only access using the proper accessor functions.
NOTE! Opaqueness and "accessor functions" are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely zero portably accessible information there.
(b) Clear integer types, where the abstraction helps avoid confusion whether it is "int" or "long".
u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.
NOTE! Again - there needs to be a reason for this. If something is "unsigned long", then there's no reason to do
typedef unsigned long myflags_t;
but if there is a clear reason for why it under certain circumstances might be an "unsigned int" and under other configurations might be "unsigned long", then by all means go ahead and use a typedef.
(c) when you use sparse to literally create a new type for type-checking.
(d) New types which are identical to standard C99 types, in certain exceptional circumstances.
Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like 'uint32_t', some people object to their use anyway.
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed equivalents which are identical to standard types are permitted -- although they are not mandatory in new code of your own.
When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.
(e) Types safe for use in userspace.
In certain structures which are visible to userspace, we cannot require C99 types and cannot use the 'u32' form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.
Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
Linux kernel coding style Chapter 5 gives great pros and cons (mostly cons) of using typedef
.
Please don't use things like "vps_t".
It's a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean?
In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
Lots of people think that typedefs "help readability". Not so. They are useful only for:
(a) totally opaque objects (where the typedef is actively used to hide what the object is).
Example: "pte_t" etc. opaque objects that you can only access using the proper accessor functions.
NOTE! Opaqueness and "accessor functions" are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely zero portably accessible information there.
(b) Clear integer types, where the abstraction helps avoid confusion whether it is "int" or "long".
u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.
NOTE! Again - there needs to be a reason for this. If something is "unsigned long", then there's no reason to do
typedef unsigned long myflags_t;
but if there is a clear reason for why it under certain circumstances might be an "unsigned int" and under other configurations might be "unsigned long", then by all means go ahead and use a typedef.
(c) when you use sparse to literally create a new type for type-checking.
(d) New types which are identical to standard C99 types, in certain exceptional circumstances.
Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like 'uint32_t', some people object to their use anyway.
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed equivalents which are identical to standard types are permitted -- although they are not mandatory in new code of your own.
When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.
(e) Types safe for use in userspace.
In certain structures which are visible to userspace, we cannot require C99 types and cannot use the 'u32' form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.
Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
edited Oct 27 '13 at 13:27
svick
176k40297414
176k40297414
answered Aug 7 '13 at 14:19
Yu HaoYu Hao
98.5k22173225
98.5k22173225
4
'Opaqueness and "accessor functions" are not good in themselves'. Can someone explain why? I would think information hiding and encapsulation would be a very good idea.
– Yawar
Dec 4 '16 at 5:48
5
@Yawar I just read this document and had exactly the same thought. Sure, C isn't object orientated, but abstraction is still a thing.
– Baldrickk
Jan 10 '17 at 16:18
add a comment |
4
'Opaqueness and "accessor functions" are not good in themselves'. Can someone explain why? I would think information hiding and encapsulation would be a very good idea.
– Yawar
Dec 4 '16 at 5:48
5
@Yawar I just read this document and had exactly the same thought. Sure, C isn't object orientated, but abstraction is still a thing.
– Baldrickk
Jan 10 '17 at 16:18
4
4
'Opaqueness and "accessor functions" are not good in themselves'. Can someone explain why? I would think information hiding and encapsulation would be a very good idea.
– Yawar
Dec 4 '16 at 5:48
'Opaqueness and "accessor functions" are not good in themselves'. Can someone explain why? I would think information hiding and encapsulation would be a very good idea.
– Yawar
Dec 4 '16 at 5:48
5
5
@Yawar I just read this document and had exactly the same thought. Sure, C isn't object orientated, but abstraction is still a thing.
– Baldrickk
Jan 10 '17 at 16:18
@Yawar I just read this document and had exactly the same thought. Sure, C isn't object orientated, but abstraction is still a thing.
– Baldrickk
Jan 10 '17 at 16:18
add a comment |
I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.
Style:
Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.
Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.
Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.
9
Clean would be not repeatingstruct
everywhere... Typedef's make new types. What do you use? Types. We don't care if it's a struct, union, or enum, that's why we typedef it.
– GManNickG
May 29 '10 at 7:14
10
No, we do care if it's a struct or union, versus an enum or some atomic type. You can't coerce a struct to an integer or to a pointer (or to any other type, for that matter), which is all you sometimes have to store some context. Having the 'struct' or 'union' keywords around improves locality of reasoning. Nobody says you need to know what's inside the struct.
– Bernd Jendrissek
Nov 26 '12 at 3:59
1
@BerndJendrissek: Structs and unions are different from other types, but should client code care about which of those two things (struct or union) something like aFILE
is?
– supercat
Mar 27 '15 at 18:54
3
@supercat FILE is a good use of typedef. I think that typedef is overused, not that it's a misfeature of the language. IMHO using typedef for everything is the "speculative overgenerality" code smell. Notice that you declare variables as FILE *foo, never as FILE foo. To me, this matters.
– Bernd Jendrissek
Mar 29 '15 at 17:16
1
@supercat: "If file-identifying variables were of type FILE rather than FILE* ..." But that's exactly the ambiguity that typedefs enable! We're just used to fopen taking a FILE * so we don't fret about it, but each time you add typedef you're introducing yet another bit of cognitive overhead: does this API want foo_t args or foo_t *? Explicitly carrying the 'struct' along improves locality of reasoning, if at the cost of a few more characters per function definition.
– Bernd Jendrissek
Mar 30 '15 at 18:47
|
show 4 more comments
I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.
Style:
Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.
Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.
Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.
9
Clean would be not repeatingstruct
everywhere... Typedef's make new types. What do you use? Types. We don't care if it's a struct, union, or enum, that's why we typedef it.
– GManNickG
May 29 '10 at 7:14
10
No, we do care if it's a struct or union, versus an enum or some atomic type. You can't coerce a struct to an integer or to a pointer (or to any other type, for that matter), which is all you sometimes have to store some context. Having the 'struct' or 'union' keywords around improves locality of reasoning. Nobody says you need to know what's inside the struct.
– Bernd Jendrissek
Nov 26 '12 at 3:59
1
@BerndJendrissek: Structs and unions are different from other types, but should client code care about which of those two things (struct or union) something like aFILE
is?
– supercat
Mar 27 '15 at 18:54
3
@supercat FILE is a good use of typedef. I think that typedef is overused, not that it's a misfeature of the language. IMHO using typedef for everything is the "speculative overgenerality" code smell. Notice that you declare variables as FILE *foo, never as FILE foo. To me, this matters.
– Bernd Jendrissek
Mar 29 '15 at 17:16
1
@supercat: "If file-identifying variables were of type FILE rather than FILE* ..." But that's exactly the ambiguity that typedefs enable! We're just used to fopen taking a FILE * so we don't fret about it, but each time you add typedef you're introducing yet another bit of cognitive overhead: does this API want foo_t args or foo_t *? Explicitly carrying the 'struct' along improves locality of reasoning, if at the cost of a few more characters per function definition.
– Bernd Jendrissek
Mar 30 '15 at 18:47
|
show 4 more comments
I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.
Style:
Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.
Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.
Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.
I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.
Style:
Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.
Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.
Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.
edited Jun 29 '18 at 18:52
KIN
404410
404410
answered May 29 '10 at 7:12
natersoznatersoz
98711421
98711421
9
Clean would be not repeatingstruct
everywhere... Typedef's make new types. What do you use? Types. We don't care if it's a struct, union, or enum, that's why we typedef it.
– GManNickG
May 29 '10 at 7:14
10
No, we do care if it's a struct or union, versus an enum or some atomic type. You can't coerce a struct to an integer or to a pointer (or to any other type, for that matter), which is all you sometimes have to store some context. Having the 'struct' or 'union' keywords around improves locality of reasoning. Nobody says you need to know what's inside the struct.
– Bernd Jendrissek
Nov 26 '12 at 3:59
1
@BerndJendrissek: Structs and unions are different from other types, but should client code care about which of those two things (struct or union) something like aFILE
is?
– supercat
Mar 27 '15 at 18:54
3
@supercat FILE is a good use of typedef. I think that typedef is overused, not that it's a misfeature of the language. IMHO using typedef for everything is the "speculative overgenerality" code smell. Notice that you declare variables as FILE *foo, never as FILE foo. To me, this matters.
– Bernd Jendrissek
Mar 29 '15 at 17:16
1
@supercat: "If file-identifying variables were of type FILE rather than FILE* ..." But that's exactly the ambiguity that typedefs enable! We're just used to fopen taking a FILE * so we don't fret about it, but each time you add typedef you're introducing yet another bit of cognitive overhead: does this API want foo_t args or foo_t *? Explicitly carrying the 'struct' along improves locality of reasoning, if at the cost of a few more characters per function definition.
– Bernd Jendrissek
Mar 30 '15 at 18:47
|
show 4 more comments
9
Clean would be not repeatingstruct
everywhere... Typedef's make new types. What do you use? Types. We don't care if it's a struct, union, or enum, that's why we typedef it.
– GManNickG
May 29 '10 at 7:14
10
No, we do care if it's a struct or union, versus an enum or some atomic type. You can't coerce a struct to an integer or to a pointer (or to any other type, for that matter), which is all you sometimes have to store some context. Having the 'struct' or 'union' keywords around improves locality of reasoning. Nobody says you need to know what's inside the struct.
– Bernd Jendrissek
Nov 26 '12 at 3:59
1
@BerndJendrissek: Structs and unions are different from other types, but should client code care about which of those two things (struct or union) something like aFILE
is?
– supercat
Mar 27 '15 at 18:54
3
@supercat FILE is a good use of typedef. I think that typedef is overused, not that it's a misfeature of the language. IMHO using typedef for everything is the "speculative overgenerality" code smell. Notice that you declare variables as FILE *foo, never as FILE foo. To me, this matters.
– Bernd Jendrissek
Mar 29 '15 at 17:16
1
@supercat: "If file-identifying variables were of type FILE rather than FILE* ..." But that's exactly the ambiguity that typedefs enable! We're just used to fopen taking a FILE * so we don't fret about it, but each time you add typedef you're introducing yet another bit of cognitive overhead: does this API want foo_t args or foo_t *? Explicitly carrying the 'struct' along improves locality of reasoning, if at the cost of a few more characters per function definition.
– Bernd Jendrissek
Mar 30 '15 at 18:47
9
9
Clean would be not repeating
struct
everywhere... Typedef's make new types. What do you use? Types. We don't care if it's a struct, union, or enum, that's why we typedef it.– GManNickG
May 29 '10 at 7:14
Clean would be not repeating
struct
everywhere... Typedef's make new types. What do you use? Types. We don't care if it's a struct, union, or enum, that's why we typedef it.– GManNickG
May 29 '10 at 7:14
10
10
No, we do care if it's a struct or union, versus an enum or some atomic type. You can't coerce a struct to an integer or to a pointer (or to any other type, for that matter), which is all you sometimes have to store some context. Having the 'struct' or 'union' keywords around improves locality of reasoning. Nobody says you need to know what's inside the struct.
– Bernd Jendrissek
Nov 26 '12 at 3:59
No, we do care if it's a struct or union, versus an enum or some atomic type. You can't coerce a struct to an integer or to a pointer (or to any other type, for that matter), which is all you sometimes have to store some context. Having the 'struct' or 'union' keywords around improves locality of reasoning. Nobody says you need to know what's inside the struct.
– Bernd Jendrissek
Nov 26 '12 at 3:59
1
1
@BerndJendrissek: Structs and unions are different from other types, but should client code care about which of those two things (struct or union) something like a
FILE
is?– supercat
Mar 27 '15 at 18:54
@BerndJendrissek: Structs and unions are different from other types, but should client code care about which of those two things (struct or union) something like a
FILE
is?– supercat
Mar 27 '15 at 18:54
3
3
@supercat FILE is a good use of typedef. I think that typedef is overused, not that it's a misfeature of the language. IMHO using typedef for everything is the "speculative overgenerality" code smell. Notice that you declare variables as FILE *foo, never as FILE foo. To me, this matters.
– Bernd Jendrissek
Mar 29 '15 at 17:16
@supercat FILE is a good use of typedef. I think that typedef is overused, not that it's a misfeature of the language. IMHO using typedef for everything is the "speculative overgenerality" code smell. Notice that you declare variables as FILE *foo, never as FILE foo. To me, this matters.
– Bernd Jendrissek
Mar 29 '15 at 17:16
1
1
@supercat: "If file-identifying variables were of type FILE rather than FILE* ..." But that's exactly the ambiguity that typedefs enable! We're just used to fopen taking a FILE * so we don't fret about it, but each time you add typedef you're introducing yet another bit of cognitive overhead: does this API want foo_t args or foo_t *? Explicitly carrying the 'struct' along improves locality of reasoning, if at the cost of a few more characters per function definition.
– Bernd Jendrissek
Mar 30 '15 at 18:47
@supercat: "If file-identifying variables were of type FILE rather than FILE* ..." But that's exactly the ambiguity that typedefs enable! We're just used to fopen taking a FILE * so we don't fret about it, but each time you add typedef you're introducing yet another bit of cognitive overhead: does this API want foo_t args or foo_t *? Explicitly carrying the 'struct' along improves locality of reasoning, if at the cost of a few more characters per function definition.
– Bernd Jendrissek
Mar 30 '15 at 18:47
|
show 4 more comments
It turns out that there are pros and cons. A useful source of information is the seminal book "Expert C Programming" (Chapter 3). Briefly, in C you have multiple namespaces: tags, types, member names and identifiers. typedef
introduces an alias for a type and locates it in the tag namespace. Namely,
typedef struct Tag{
...members...
}Type;
defines two things. One Tag in the tag namespace and one Type in the type namespace. So you can do both Type myType
and struct Tag myTagType
. Declarations like struct Type myType
or Tag myTagType
are illegal. In addition, in a declaration like this:
typedef Type *Type_ptr;
we define a pointer to our Type. So if we declare:
Type_ptr var1, var2;
struct Tag *myTagType1, myTagType2;
then var1
,var2
and myTagType1
are pointers to Type but myTagType2
not.
In the above-mentioned book, it mentions that typedefing structs are not very useful as it only saves the programmer from writing the word struct. However, I have an objection, like many other C programmers. Although it sometimes turns to obfuscate some names (that's why it is not advisable in large code bases like the kernel) when you want to implement polymorphism in C it helps a lot look here for details. Example:
typedef struct MyWriter_t{
MyPipe super;
MyQueue relative;
uint32_t flags;
...
}MyWriter;
you can do:
void my_writer_func(MyPipe *s)
{
MyWriter *self = (MyWriter *) s;
uint32_t myFlags = self->flags;
...
}
So you can access an outer member (flags
) by the inner struct (MyPipe
) through casting. For me it is less confusing to cast the whole type than doing (struct MyWriter_ *) s;
every time you want to perform such functionality. In these cases brief referencing is a big deal especially if you heavily employ the technique in your code.
Finally, the last aspect with typedef
ed types is the inability to extend them, in contrast to macros. If for example, you have:
#define X char[10] or
typedef char Y[10]
you can then declare
unsigned X x; but not
unsigned Y y;
We do not really care for this for structs because it does not apply to storage specifiers (volatile
and const
).
1
MyPipe *s; MyWriter *self = (MyWriter *) s;
and you've just broken strict aliasing.
– Jonathon Reinhart
Jun 1 '15 at 19:18
@JonathonReinhart It would be illustrative to mention how this can be avoided, for example how the hugely cast-happy GTK+ works around it: bugzilla.gnome.org/show_bug.cgi?id=140722 / mail.gnome.org/archives/gtk-devel-list/2004-April/msg00196.html
– underscore_d
Apr 9 '16 at 16:35
"typedef introduces an alias for a type and locates it in the tag namespace. Namely"typedef struct Tag{ ...members... }Type;
"defines two things" doesn't quite make sense. if typedef defines tags then 'Type' here should also be a tag. The truth is the definition defines 2 tags and 1 type (or 2 types and 1 tag. not sure):struct Tag
,Tag
andType
.struct Tag
is definitely a type.Tag
is a tag. but the confusion is whetherType
is a tag or a type
– Qwertyzw
May 11 '18 at 13:39
add a comment |
It turns out that there are pros and cons. A useful source of information is the seminal book "Expert C Programming" (Chapter 3). Briefly, in C you have multiple namespaces: tags, types, member names and identifiers. typedef
introduces an alias for a type and locates it in the tag namespace. Namely,
typedef struct Tag{
...members...
}Type;
defines two things. One Tag in the tag namespace and one Type in the type namespace. So you can do both Type myType
and struct Tag myTagType
. Declarations like struct Type myType
or Tag myTagType
are illegal. In addition, in a declaration like this:
typedef Type *Type_ptr;
we define a pointer to our Type. So if we declare:
Type_ptr var1, var2;
struct Tag *myTagType1, myTagType2;
then var1
,var2
and myTagType1
are pointers to Type but myTagType2
not.
In the above-mentioned book, it mentions that typedefing structs are not very useful as it only saves the programmer from writing the word struct. However, I have an objection, like many other C programmers. Although it sometimes turns to obfuscate some names (that's why it is not advisable in large code bases like the kernel) when you want to implement polymorphism in C it helps a lot look here for details. Example:
typedef struct MyWriter_t{
MyPipe super;
MyQueue relative;
uint32_t flags;
...
}MyWriter;
you can do:
void my_writer_func(MyPipe *s)
{
MyWriter *self = (MyWriter *) s;
uint32_t myFlags = self->flags;
...
}
So you can access an outer member (flags
) by the inner struct (MyPipe
) through casting. For me it is less confusing to cast the whole type than doing (struct MyWriter_ *) s;
every time you want to perform such functionality. In these cases brief referencing is a big deal especially if you heavily employ the technique in your code.
Finally, the last aspect with typedef
ed types is the inability to extend them, in contrast to macros. If for example, you have:
#define X char[10] or
typedef char Y[10]
you can then declare
unsigned X x; but not
unsigned Y y;
We do not really care for this for structs because it does not apply to storage specifiers (volatile
and const
).
1
MyPipe *s; MyWriter *self = (MyWriter *) s;
and you've just broken strict aliasing.
– Jonathon Reinhart
Jun 1 '15 at 19:18
@JonathonReinhart It would be illustrative to mention how this can be avoided, for example how the hugely cast-happy GTK+ works around it: bugzilla.gnome.org/show_bug.cgi?id=140722 / mail.gnome.org/archives/gtk-devel-list/2004-April/msg00196.html
– underscore_d
Apr 9 '16 at 16:35
"typedef introduces an alias for a type and locates it in the tag namespace. Namely"typedef struct Tag{ ...members... }Type;
"defines two things" doesn't quite make sense. if typedef defines tags then 'Type' here should also be a tag. The truth is the definition defines 2 tags and 1 type (or 2 types and 1 tag. not sure):struct Tag
,Tag
andType
.struct Tag
is definitely a type.Tag
is a tag. but the confusion is whetherType
is a tag or a type
– Qwertyzw
May 11 '18 at 13:39
add a comment |
It turns out that there are pros and cons. A useful source of information is the seminal book "Expert C Programming" (Chapter 3). Briefly, in C you have multiple namespaces: tags, types, member names and identifiers. typedef
introduces an alias for a type and locates it in the tag namespace. Namely,
typedef struct Tag{
...members...
}Type;
defines two things. One Tag in the tag namespace and one Type in the type namespace. So you can do both Type myType
and struct Tag myTagType
. Declarations like struct Type myType
or Tag myTagType
are illegal. In addition, in a declaration like this:
typedef Type *Type_ptr;
we define a pointer to our Type. So if we declare:
Type_ptr var1, var2;
struct Tag *myTagType1, myTagType2;
then var1
,var2
and myTagType1
are pointers to Type but myTagType2
not.
In the above-mentioned book, it mentions that typedefing structs are not very useful as it only saves the programmer from writing the word struct. However, I have an objection, like many other C programmers. Although it sometimes turns to obfuscate some names (that's why it is not advisable in large code bases like the kernel) when you want to implement polymorphism in C it helps a lot look here for details. Example:
typedef struct MyWriter_t{
MyPipe super;
MyQueue relative;
uint32_t flags;
...
}MyWriter;
you can do:
void my_writer_func(MyPipe *s)
{
MyWriter *self = (MyWriter *) s;
uint32_t myFlags = self->flags;
...
}
So you can access an outer member (flags
) by the inner struct (MyPipe
) through casting. For me it is less confusing to cast the whole type than doing (struct MyWriter_ *) s;
every time you want to perform such functionality. In these cases brief referencing is a big deal especially if you heavily employ the technique in your code.
Finally, the last aspect with typedef
ed types is the inability to extend them, in contrast to macros. If for example, you have:
#define X char[10] or
typedef char Y[10]
you can then declare
unsigned X x; but not
unsigned Y y;
We do not really care for this for structs because it does not apply to storage specifiers (volatile
and const
).
It turns out that there are pros and cons. A useful source of information is the seminal book "Expert C Programming" (Chapter 3). Briefly, in C you have multiple namespaces: tags, types, member names and identifiers. typedef
introduces an alias for a type and locates it in the tag namespace. Namely,
typedef struct Tag{
...members...
}Type;
defines two things. One Tag in the tag namespace and one Type in the type namespace. So you can do both Type myType
and struct Tag myTagType
. Declarations like struct Type myType
or Tag myTagType
are illegal. In addition, in a declaration like this:
typedef Type *Type_ptr;
we define a pointer to our Type. So if we declare:
Type_ptr var1, var2;
struct Tag *myTagType1, myTagType2;
then var1
,var2
and myTagType1
are pointers to Type but myTagType2
not.
In the above-mentioned book, it mentions that typedefing structs are not very useful as it only saves the programmer from writing the word struct. However, I have an objection, like many other C programmers. Although it sometimes turns to obfuscate some names (that's why it is not advisable in large code bases like the kernel) when you want to implement polymorphism in C it helps a lot look here for details. Example:
typedef struct MyWriter_t{
MyPipe super;
MyQueue relative;
uint32_t flags;
...
}MyWriter;
you can do:
void my_writer_func(MyPipe *s)
{
MyWriter *self = (MyWriter *) s;
uint32_t myFlags = self->flags;
...
}
So you can access an outer member (flags
) by the inner struct (MyPipe
) through casting. For me it is less confusing to cast the whole type than doing (struct MyWriter_ *) s;
every time you want to perform such functionality. In these cases brief referencing is a big deal especially if you heavily employ the technique in your code.
Finally, the last aspect with typedef
ed types is the inability to extend them, in contrast to macros. If for example, you have:
#define X char[10] or
typedef char Y[10]
you can then declare
unsigned X x; but not
unsigned Y y;
We do not really care for this for structs because it does not apply to storage specifiers (volatile
and const
).
edited Jun 29 '18 at 13:59
KIN
404410
404410
answered Aug 11 '13 at 15:48
user1533288user1533288
12125
12125
1
MyPipe *s; MyWriter *self = (MyWriter *) s;
and you've just broken strict aliasing.
– Jonathon Reinhart
Jun 1 '15 at 19:18
@JonathonReinhart It would be illustrative to mention how this can be avoided, for example how the hugely cast-happy GTK+ works around it: bugzilla.gnome.org/show_bug.cgi?id=140722 / mail.gnome.org/archives/gtk-devel-list/2004-April/msg00196.html
– underscore_d
Apr 9 '16 at 16:35
"typedef introduces an alias for a type and locates it in the tag namespace. Namely"typedef struct Tag{ ...members... }Type;
"defines two things" doesn't quite make sense. if typedef defines tags then 'Type' here should also be a tag. The truth is the definition defines 2 tags and 1 type (or 2 types and 1 tag. not sure):struct Tag
,Tag
andType
.struct Tag
is definitely a type.Tag
is a tag. but the confusion is whetherType
is a tag or a type
– Qwertyzw
May 11 '18 at 13:39
add a comment |
1
MyPipe *s; MyWriter *self = (MyWriter *) s;
and you've just broken strict aliasing.
– Jonathon Reinhart
Jun 1 '15 at 19:18
@JonathonReinhart It would be illustrative to mention how this can be avoided, for example how the hugely cast-happy GTK+ works around it: bugzilla.gnome.org/show_bug.cgi?id=140722 / mail.gnome.org/archives/gtk-devel-list/2004-April/msg00196.html
– underscore_d
Apr 9 '16 at 16:35
"typedef introduces an alias for a type and locates it in the tag namespace. Namely"typedef struct Tag{ ...members... }Type;
"defines two things" doesn't quite make sense. if typedef defines tags then 'Type' here should also be a tag. The truth is the definition defines 2 tags and 1 type (or 2 types and 1 tag. not sure):struct Tag
,Tag
andType
.struct Tag
is definitely a type.Tag
is a tag. but the confusion is whetherType
is a tag or a type
– Qwertyzw
May 11 '18 at 13:39
1
1
MyPipe *s; MyWriter *self = (MyWriter *) s;
and you've just broken strict aliasing.– Jonathon Reinhart
Jun 1 '15 at 19:18
MyPipe *s; MyWriter *self = (MyWriter *) s;
and you've just broken strict aliasing.– Jonathon Reinhart
Jun 1 '15 at 19:18
@JonathonReinhart It would be illustrative to mention how this can be avoided, for example how the hugely cast-happy GTK+ works around it: bugzilla.gnome.org/show_bug.cgi?id=140722 / mail.gnome.org/archives/gtk-devel-list/2004-April/msg00196.html
– underscore_d
Apr 9 '16 at 16:35
@JonathonReinhart It would be illustrative to mention how this can be avoided, for example how the hugely cast-happy GTK+ works around it: bugzilla.gnome.org/show_bug.cgi?id=140722 / mail.gnome.org/archives/gtk-devel-list/2004-April/msg00196.html
– underscore_d
Apr 9 '16 at 16:35
"typedef introduces an alias for a type and locates it in the tag namespace. Namely"
typedef struct Tag{ ...members... }Type;
"defines two things" doesn't quite make sense. if typedef defines tags then 'Type' here should also be a tag. The truth is the definition defines 2 tags and 1 type (or 2 types and 1 tag. not sure): struct Tag
, Tag
and Type
. struct Tag
is definitely a type. Tag
is a tag. but the confusion is whether Type
is a tag or a type– Qwertyzw
May 11 '18 at 13:39
"typedef introduces an alias for a type and locates it in the tag namespace. Namely"
typedef struct Tag{ ...members... }Type;
"defines two things" doesn't quite make sense. if typedef defines tags then 'Type' here should also be a tag. The truth is the definition defines 2 tags and 1 type (or 2 types and 1 tag. not sure): struct Tag
, Tag
and Type
. struct Tag
is definitely a type. Tag
is a tag. but the confusion is whether Type
is a tag or a type– Qwertyzw
May 11 '18 at 13:39
add a comment |
Let's start with the basics and work our way up.
Here is an example of Structure definition:
struct point
{
int x, y;
};
Here the name point
is optional.
A Structure can be declared during its definition or after.
Declaring during definition
struct point
{
int x, y;
} first_point, second_point;
Declaring after definition
struct point
{
int x, y;
};
struct point first_point, second_point;
Now, carefully note the last case above; you need to write struct point
to declare Structures of that type if you decide to create that type at a later point in your code.
Enter typedef
. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using typedef
during its definition might be a good idea since you can save some typing moving forward.
typedef struct point
{
int x, y;
} Points;
Points first_point, second_point;
A word of caution while naming your custom type
Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.
add a comment |
Let's start with the basics and work our way up.
Here is an example of Structure definition:
struct point
{
int x, y;
};
Here the name point
is optional.
A Structure can be declared during its definition or after.
Declaring during definition
struct point
{
int x, y;
} first_point, second_point;
Declaring after definition
struct point
{
int x, y;
};
struct point first_point, second_point;
Now, carefully note the last case above; you need to write struct point
to declare Structures of that type if you decide to create that type at a later point in your code.
Enter typedef
. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using typedef
during its definition might be a good idea since you can save some typing moving forward.
typedef struct point
{
int x, y;
} Points;
Points first_point, second_point;
A word of caution while naming your custom type
Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.
add a comment |
Let's start with the basics and work our way up.
Here is an example of Structure definition:
struct point
{
int x, y;
};
Here the name point
is optional.
A Structure can be declared during its definition or after.
Declaring during definition
struct point
{
int x, y;
} first_point, second_point;
Declaring after definition
struct point
{
int x, y;
};
struct point first_point, second_point;
Now, carefully note the last case above; you need to write struct point
to declare Structures of that type if you decide to create that type at a later point in your code.
Enter typedef
. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using typedef
during its definition might be a good idea since you can save some typing moving forward.
typedef struct point
{
int x, y;
} Points;
Points first_point, second_point;
A word of caution while naming your custom type
Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.
Let's start with the basics and work our way up.
Here is an example of Structure definition:
struct point
{
int x, y;
};
Here the name point
is optional.
A Structure can be declared during its definition or after.
Declaring during definition
struct point
{
int x, y;
} first_point, second_point;
Declaring after definition
struct point
{
int x, y;
};
struct point first_point, second_point;
Now, carefully note the last case above; you need to write struct point
to declare Structures of that type if you decide to create that type at a later point in your code.
Enter typedef
. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using typedef
during its definition might be a good idea since you can save some typing moving forward.
typedef struct point
{
int x, y;
} Points;
Points first_point, second_point;
A word of caution while naming your custom type
Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.
edited Jun 29 '18 at 13:42
KIN
404410
404410
answered Mar 9 '18 at 18:16
AsifAsif
8418
8418
add a comment |
add a comment |
the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.
GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:
struct MyStruct
{
int i;
};
// The following is legal in C++:
MyStruct obj;
obj.i = 7;
add a comment |
the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.
GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:
struct MyStruct
{
int i;
};
// The following is legal in C++:
MyStruct obj;
obj.i = 7;
add a comment |
the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.
GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:
struct MyStruct
{
int i;
};
// The following is legal in C++:
MyStruct obj;
obj.i = 7;
the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.
GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:
struct MyStruct
{
int i;
};
// The following is legal in C++:
MyStruct obj;
obj.i = 7;
answered Oct 31 '08 at 8:24
philsquaredphilsquared
17.6k106094
17.6k106094
add a comment |
add a comment |
typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
Of course you can always add:
typedef struct foo foo_t;
typedef struct bar bar_t;
What exactly is the point of that?
add a comment |
typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
Of course you can always add:
typedef struct foo foo_t;
typedef struct bar bar_t;
What exactly is the point of that?
add a comment |
typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
Of course you can always add:
typedef struct foo foo_t;
typedef struct bar bar_t;
What exactly is the point of that?
typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
Of course you can always add:
typedef struct foo foo_t;
typedef struct bar bar_t;
What exactly is the point of that?
answered Jan 30 '16 at 15:47
natersoznatersoz
98711421
98711421
add a comment |
add a comment |
A>
a typdef aids in the meaning and documentation of a program by allowing creation of more meaningful synonyms for data types. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).
B>
a structure defines a type. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit
C>
typedef'ing a struct is explained in A above.
D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames.
add a comment |
A>
a typdef aids in the meaning and documentation of a program by allowing creation of more meaningful synonyms for data types. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).
B>
a structure defines a type. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit
C>
typedef'ing a struct is explained in A above.
D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames.
add a comment |
A>
a typdef aids in the meaning and documentation of a program by allowing creation of more meaningful synonyms for data types. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).
B>
a structure defines a type. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit
C>
typedef'ing a struct is explained in A above.
D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames.
A>
a typdef aids in the meaning and documentation of a program by allowing creation of more meaningful synonyms for data types. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).
B>
a structure defines a type. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit
C>
typedef'ing a struct is explained in A above.
D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames.
answered Jul 5 '17 at 0:19
JamesAD-0JamesAD-0
60565
60565
add a comment |
add a comment |
Turns out in C99 typedef is required. It is outdated, but a lot of tools (ala HackRank) use c99 as its pure C implementation. And typedef is required there.
I'm not saying they should change (maybe have two C options) if the requirement changed, those of us studing for interviews on the site would be SOL.
2
"Turns out in C99typedef
is required." What do you mean?
– Julien Lopez
Nov 2 '16 at 9:54
The question is aboutC
, notC++
. InC
typedefs are 'required' (and will most likely always be). 'Required' as in, you will not be able to declare a variablePoint varName;
and have the type be synonymous withstruct Point;
without atypedef struct Point Point;
.
– YoYoYonnY
Nov 30 '16 at 21:26
add a comment |
Turns out in C99 typedef is required. It is outdated, but a lot of tools (ala HackRank) use c99 as its pure C implementation. And typedef is required there.
I'm not saying they should change (maybe have two C options) if the requirement changed, those of us studing for interviews on the site would be SOL.
2
"Turns out in C99typedef
is required." What do you mean?
– Julien Lopez
Nov 2 '16 at 9:54
The question is aboutC
, notC++
. InC
typedefs are 'required' (and will most likely always be). 'Required' as in, you will not be able to declare a variablePoint varName;
and have the type be synonymous withstruct Point;
without atypedef struct Point Point;
.
– YoYoYonnY
Nov 30 '16 at 21:26
add a comment |
Turns out in C99 typedef is required. It is outdated, but a lot of tools (ala HackRank) use c99 as its pure C implementation. And typedef is required there.
I'm not saying they should change (maybe have two C options) if the requirement changed, those of us studing for interviews on the site would be SOL.
Turns out in C99 typedef is required. It is outdated, but a lot of tools (ala HackRank) use c99 as its pure C implementation. And typedef is required there.
I'm not saying they should change (maybe have two C options) if the requirement changed, those of us studing for interviews on the site would be SOL.
answered Nov 2 '16 at 9:34
Matthew Corey BrownMatthew Corey Brown
11
11
2
"Turns out in C99typedef
is required." What do you mean?
– Julien Lopez
Nov 2 '16 at 9:54
The question is aboutC
, notC++
. InC
typedefs are 'required' (and will most likely always be). 'Required' as in, you will not be able to declare a variablePoint varName;
and have the type be synonymous withstruct Point;
without atypedef struct Point Point;
.
– YoYoYonnY
Nov 30 '16 at 21:26
add a comment |
2
"Turns out in C99typedef
is required." What do you mean?
– Julien Lopez
Nov 2 '16 at 9:54
The question is aboutC
, notC++
. InC
typedefs are 'required' (and will most likely always be). 'Required' as in, you will not be able to declare a variablePoint varName;
and have the type be synonymous withstruct Point;
without atypedef struct Point Point;
.
– YoYoYonnY
Nov 30 '16 at 21:26
2
2
"Turns out in C99
typedef
is required." What do you mean?– Julien Lopez
Nov 2 '16 at 9:54
"Turns out in C99
typedef
is required." What do you mean?– Julien Lopez
Nov 2 '16 at 9:54
The question is about
C
, not C++
. In C
typedefs are 'required' (and will most likely always be). 'Required' as in, you will not be able to declare a variable Point varName;
and have the type be synonymous with struct Point;
without a typedef struct Point Point;
.– YoYoYonnY
Nov 30 '16 at 21:26
The question is about
C
, not C++
. In C
typedefs are 'required' (and will most likely always be). 'Required' as in, you will not be able to declare a variable Point varName;
and have the type be synonymous with struct Point;
without a typedef struct Point Point;
.– YoYoYonnY
Nov 30 '16 at 21:26
add a comment |
In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'.
In 'C' we often declare a 'struct' outside of the 'main' function. For example:
struct complex{ int real_part, img_part }COMPLEX;
main(){
struct KOMPLEKS number; // number type is now a struct type
number.real_part = 3;
number.img_part = -1;
printf("Number: %d.%d i n",number.real_part, number.img_part);
}
Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:
typedef struct complex{int real_part, img_part; }COMPLEX;
//now COMPLEX is the new name for this structure and if I want to use it without
// a keyword like in the first example 'struct complex number'.
main(){
COMPLEX number; // number is now the same type as in the first example
number.real_part = 1;
number.img)part = 5;
printf("%d %d n", number.real_part, number.img_part);
}
If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'.
add a comment |
In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'.
In 'C' we often declare a 'struct' outside of the 'main' function. For example:
struct complex{ int real_part, img_part }COMPLEX;
main(){
struct KOMPLEKS number; // number type is now a struct type
number.real_part = 3;
number.img_part = -1;
printf("Number: %d.%d i n",number.real_part, number.img_part);
}
Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:
typedef struct complex{int real_part, img_part; }COMPLEX;
//now COMPLEX is the new name for this structure and if I want to use it without
// a keyword like in the first example 'struct complex number'.
main(){
COMPLEX number; // number is now the same type as in the first example
number.real_part = 1;
number.img)part = 5;
printf("%d %d n", number.real_part, number.img_part);
}
If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'.
add a comment |
In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'.
In 'C' we often declare a 'struct' outside of the 'main' function. For example:
struct complex{ int real_part, img_part }COMPLEX;
main(){
struct KOMPLEKS number; // number type is now a struct type
number.real_part = 3;
number.img_part = -1;
printf("Number: %d.%d i n",number.real_part, number.img_part);
}
Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:
typedef struct complex{int real_part, img_part; }COMPLEX;
//now COMPLEX is the new name for this structure and if I want to use it without
// a keyword like in the first example 'struct complex number'.
main(){
COMPLEX number; // number is now the same type as in the first example
number.real_part = 1;
number.img)part = 5;
printf("%d %d n", number.real_part, number.img_part);
}
If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'.
In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'.
In 'C' we often declare a 'struct' outside of the 'main' function. For example:
struct complex{ int real_part, img_part }COMPLEX;
main(){
struct KOMPLEKS number; // number type is now a struct type
number.real_part = 3;
number.img_part = -1;
printf("Number: %d.%d i n",number.real_part, number.img_part);
}
Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:
typedef struct complex{int real_part, img_part; }COMPLEX;
//now COMPLEX is the new name for this structure and if I want to use it without
// a keyword like in the first example 'struct complex number'.
main(){
COMPLEX number; // number is now the same type as in the first example
number.real_part = 1;
number.img)part = 5;
printf("%d %d n", number.real_part, number.img_part);
}
If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'.
edited Jun 29 '18 at 13:34
KIN
404410
404410
answered Jun 11 '16 at 0:50
RichardGeerifyRichardGeerify
12
12
add a comment |
add a comment |
At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat "#include" and other)
so :
struct a
{
int i;
};
struct b
{
struct a;
int i;
int j;
};
struct b is expended as something like this :
struct b
{
struct a
{
int i;
};
int i;
int j;
}
and so, at compile time it evolve on stack as something like:
b:
int ai
int i
int j
that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.
typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :
typedef struct a A; //anticipated declaration for member declaration
typedef struct a //Implemented declaration
{
A* b; // member declaration
}A;
is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions.
This mean that in C typedefs are more near as C++ class than lonely structs.
3
It isn't difficult to have self-referential structs at all. struct foo { struct foo *next; int thing; }
– Bernd Jendrissek
Mar 30 '15 at 18:52
4
...what? Saying preprocessor to describe the resolution ofstructs
andtypedef
s is bad enough, but the rest of your writing is so confusing that I find it hard to get any message from it. One thing I can say, though, is that your idea that a non-typedef
dstruct
cannot be forward-declared or used as an opaque (pointer) member is totally false. In your 1st example,struct b
can trivially contain astruct a *
, notypedef
required. The assertions thatstruct
s are merely dumb pieces of macro-expansion, and thattypedef
s give them revolutionary new powers, are painfully incorrect
– underscore_d
Apr 9 '16 at 16:44
add a comment |
At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat "#include" and other)
so :
struct a
{
int i;
};
struct b
{
struct a;
int i;
int j;
};
struct b is expended as something like this :
struct b
{
struct a
{
int i;
};
int i;
int j;
}
and so, at compile time it evolve on stack as something like:
b:
int ai
int i
int j
that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.
typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :
typedef struct a A; //anticipated declaration for member declaration
typedef struct a //Implemented declaration
{
A* b; // member declaration
}A;
is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions.
This mean that in C typedefs are more near as C++ class than lonely structs.
3
It isn't difficult to have self-referential structs at all. struct foo { struct foo *next; int thing; }
– Bernd Jendrissek
Mar 30 '15 at 18:52
4
...what? Saying preprocessor to describe the resolution ofstructs
andtypedef
s is bad enough, but the rest of your writing is so confusing that I find it hard to get any message from it. One thing I can say, though, is that your idea that a non-typedef
dstruct
cannot be forward-declared or used as an opaque (pointer) member is totally false. In your 1st example,struct b
can trivially contain astruct a *
, notypedef
required. The assertions thatstruct
s are merely dumb pieces of macro-expansion, and thattypedef
s give them revolutionary new powers, are painfully incorrect
– underscore_d
Apr 9 '16 at 16:44
add a comment |
At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat "#include" and other)
so :
struct a
{
int i;
};
struct b
{
struct a;
int i;
int j;
};
struct b is expended as something like this :
struct b
{
struct a
{
int i;
};
int i;
int j;
}
and so, at compile time it evolve on stack as something like:
b:
int ai
int i
int j
that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.
typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :
typedef struct a A; //anticipated declaration for member declaration
typedef struct a //Implemented declaration
{
A* b; // member declaration
}A;
is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions.
This mean that in C typedefs are more near as C++ class than lonely structs.
At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat "#include" and other)
so :
struct a
{
int i;
};
struct b
{
struct a;
int i;
int j;
};
struct b is expended as something like this :
struct b
{
struct a
{
int i;
};
int i;
int j;
}
and so, at compile time it evolve on stack as something like:
b:
int ai
int i
int j
that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.
typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :
typedef struct a A; //anticipated declaration for member declaration
typedef struct a //Implemented declaration
{
A* b; // member declaration
}A;
is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions.
This mean that in C typedefs are more near as C++ class than lonely structs.
answered Mar 6 '10 at 14:54
doccpudoccpu
211
211
3
It isn't difficult to have self-referential structs at all. struct foo { struct foo *next; int thing; }
– Bernd Jendrissek
Mar 30 '15 at 18:52
4
...what? Saying preprocessor to describe the resolution ofstructs
andtypedef
s is bad enough, but the rest of your writing is so confusing that I find it hard to get any message from it. One thing I can say, though, is that your idea that a non-typedef
dstruct
cannot be forward-declared or used as an opaque (pointer) member is totally false. In your 1st example,struct b
can trivially contain astruct a *
, notypedef
required. The assertions thatstruct
s are merely dumb pieces of macro-expansion, and thattypedef
s give them revolutionary new powers, are painfully incorrect
– underscore_d
Apr 9 '16 at 16:44
add a comment |
3
It isn't difficult to have self-referential structs at all. struct foo { struct foo *next; int thing; }
– Bernd Jendrissek
Mar 30 '15 at 18:52
4
...what? Saying preprocessor to describe the resolution ofstructs
andtypedef
s is bad enough, but the rest of your writing is so confusing that I find it hard to get any message from it. One thing I can say, though, is that your idea that a non-typedef
dstruct
cannot be forward-declared or used as an opaque (pointer) member is totally false. In your 1st example,struct b
can trivially contain astruct a *
, notypedef
required. The assertions thatstruct
s are merely dumb pieces of macro-expansion, and thattypedef
s give them revolutionary new powers, are painfully incorrect
– underscore_d
Apr 9 '16 at 16:44
3
3
It isn't difficult to have self-referential structs at all. struct foo { struct foo *next; int thing; }
– Bernd Jendrissek
Mar 30 '15 at 18:52
It isn't difficult to have self-referential structs at all. struct foo { struct foo *next; int thing; }
– Bernd Jendrissek
Mar 30 '15 at 18:52
4
4
...what? Saying preprocessor to describe the resolution of
structs
and typedef
s is bad enough, but the rest of your writing is so confusing that I find it hard to get any message from it. One thing I can say, though, is that your idea that a non-typedef
d struct
cannot be forward-declared or used as an opaque (pointer) member is totally false. In your 1st example, struct b
can trivially contain a struct a *
, no typedef
required. The assertions that struct
s are merely dumb pieces of macro-expansion, and that typedef
s give them revolutionary new powers, are painfully incorrect– underscore_d
Apr 9 '16 at 16:44
...what? Saying preprocessor to describe the resolution of
structs
and typedef
s is bad enough, but the rest of your writing is so confusing that I find it hard to get any message from it. One thing I can say, though, is that your idea that a non-typedef
d struct
cannot be forward-declared or used as an opaque (pointer) member is totally false. In your 1st example, struct b
can trivially contain a struct a *
, no typedef
required. The assertions that struct
s are merely dumb pieces of macro-expansion, and that typedef
s give them revolutionary new powers, are painfully incorrect– underscore_d
Apr 9 '16 at 16:44
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f252780%2fwhy-should-we-typedef-a-struct-so-often-in-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
13
More thorough and precise answer: stackoverflow.com/questions/612328/…
– AbiusX
Mar 17 '11 at 2:14
It has disadvantages I think you can't create a link list with anonymous struct because the line
struct * ptr
inside the struct will cause error– Raghib Ahsan
Feb 1 '16 at 17:40
5
The 'more thorough and precise answer' is Difference between struct and typedef struct in C++, and there are significant differences between C and C++ in this area which make that answer not wholly appropriate for a question about C.
– Jonathan Leffler
Jun 5 '16 at 22:21
This question has a duplicate typedef struct vs struct definitions that also has stellar answers.
– Jonathan Leffler
Jun 5 '16 at 22:25
OTOH, kernel.org/doc/html/v4.10/process/coding-style.html tells us that we shouldn't do such typedefs.
– glglgl
Mar 27 '18 at 15:52