CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2001
    Location
    United States
    Posts
    725

    Why declare struct's with keyword 'typedef'?

    Hello,

    In other people's source code, I have often seen structures declared in both of the following manners:

    struct sample {
    ...
    };

    typedef struct sample {
    ...
    };

    I do not understand why the keyword 'typedef' is used at times. When I remove the keyword, the programs appear to run in the same manner as when I have the keyword there. If someone could clarify why 'typedef' is placed before structure definitions, that would be helpful. Thanks.

    Fierytycoon

  2. #2
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    Actually, your second definition is incorrect: it should be

    typedef struct
    {
    ...
    } name;

    This is a hangover from the C days when you had to put struct in front of name if it was a structure. To make life easier, they type defined the struct to be name. In C++, because struct is just class public, there is no need to typedef struct.
    Succinct is verbose for terse

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Why declare struct's with keyword 'typedef'?

    Originally posted by Fierytycoon
    Hello,

    In other people's source code, I have often seen structures declared in both of the following manners:

    struct sample {
    ...
    };

    typedef struct sample {
    ...
    };

    I do not understand why the keyword 'typedef' is used at times. When I remove the keyword, the programs appear to run in the same manner as when I have the keyword there. If someone could clarify why 'typedef' is placed before structure definitions, that would be helpful. Thanks.

    Fierytycoon
    To add to Cup's answer, if these definitions are in a header file, and you intend to use the header in both 'C' and C++ source files, you should leave the "typedef struct" alone. The obvious reason is that the 'C' compiler will throw a fit if you declare your structure the "C++" way

    Regards,

    Paul McKenzie

  4. #4
    Join Date
    May 2001
    Location
    United States
    Posts
    725
    ah, I see. Thanks to both of you for all of your input.

    Fierytycoon

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured