Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #11744

Re: typedef struct

From Keith Thompson <kst-u@mib.org>
Newsgroups comp.lang.c
Subject Re: typedef struct
Date 2011-10-15 16:26 -0700
Organization None to speak of
Message-ID <lnk485rg3o.fsf@nuthaus.mib.org> (permalink)
References <ff89df4d-151e-4537-bb10-af6d148475b4@n13g2000vbv.googlegroups.com>

Show all headers | View raw


John McDermick <johnthedspguy@gmail.com> writes:
> If I have this definition in a header file:
>
> typedef struct A
> {
>    int test;
> } B;
>
> What exactly is A and what is B ?
>
> What does it mean when I declare like this:
>
> typedef struct A
> {
>    int test;
> };
>
> And what does it mean when I declare like this:
>
> typedef struct
> {
>    int test;
> } B;

Eric has ably answered your question.

Opinions differ on this, but personally I don't feel the need for a
typedef at all.  I'd just declare the type as

    struct A {
        int test;
    };

and then refer to it as "struct A".  There's no real need to use a
typedef to give the type another name; it already has a perfectly good
one.

(The counterargument is that many people like to have a one-word name
for the type.)

You can also use the same identifier for both the tag and the typedef:

    typedef struct A {
        int test;
    } A;

You can then refer to the type either as "struct A" or as "A".  Since
struct tags are in a different namespace than typedef names (since the
tag can only appear immediately after the keyword "struct', and the
typedef name never can), there's no conflict.

(Note that C++ makes the struct tag usable directly as a type name; even
without the typedef, you can refer to the type as just "A".  C doesn't
do this.)

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

typedef struct John McDermick <johnthedspguy@gmail.com> - 2011-10-15 11:38 -0700
  Re: typedef struct Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-10-15 15:40 -0400
  Re: typedef struct "BartC" <bc@freeuk.com> - 2011-10-15 20:42 +0100
  Re: typedef struct Keith Thompson <kst-u@mib.org> - 2011-10-15 16:26 -0700
    Re: typedef struct John McDermick <johnthedspguy@gmail.com> - 2011-10-16 09:48 -0700

csiph-web