typedefs and structs

Is the combination typedef struct used in C++? On MDSN I see stuctures under C++ code with typedef structs. I read that it was used in C to avoid typing struct everytime you needed to use a structure. E.g

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
typedef struct _HDITEM {
  UINT    mask;
  int     cxy;
  LPTSTR  pszText;
  HBITMAP hbm;
  int     cchTextMax;
  int     fmt;
  LPARAM  lParam;
#if (_WIN32_IE >= 0x0300)
  int     iImage;
  int     iOrder;
#endif 
#if (_WIN32_IE >= 0x0500)
  UINT    type;
  void    *pvFilter;
#endif 
#if (_WIN32_WINNT >= 0x0600)
  UINT    state;
#endif 
} HDITEM, *LPHDITEM;


Also what does it mean when you add things after the struct definition like above such as HDITEM and *LPHDITEM? Are these defined so you don't have type it's declaration but use it straight away?

Thanks
Last edited on
closed account (18hRX9L8)
Read up on structs here: http://www.cplusplus.com/doc/tutorial/structures/.
I read that it was used in C to avoid typing struct everytime you needed to use a structure


This is correct. In C, structs exist in a separate namespace, so if you just declare a struct "normally" you must preface it with the struct keyword whenever you instantiate it.

typedefs, on the other hand, are not put in a separate namespace, so typedefing a struct brings it into the "normal" namespace allowing you to use the name without the struct prefix.


In C++, none of that applies because structs are put in the normal namespace. Doing a typedef struct becomes optional.

Also what does it mean when you add things after the struct definition like above such as HDITEM and *LPHDITEM?


Those are the types you're typedef'ing. Those are the names that are put in the "normal" namespace. The one before the struct definition is in the struct namespace.

Example (C code):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef struct A
{
  //...
} B;

// here, 'A' is a struct name in struct namespace
// but 'B' is the struct typedef, so it exists in the normal namespace.

int main()
{
    A a;  // ERROR, 'A' undeclared
    struct A aa;  // OK
    B b;  // OK
    struct B bb;  // ERROR, redeclaring 'b' as a new struct (different from A)
};


The * name (LPHDITEM in your example) is another typedef, but for a pointer type:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// This:
typedef struct Foo
{
   //...
} *PFoo;

//=======================
// is the same as doing this:
struct Foo
{
    //...
};

typedef struct Foo* PFoo;
Topic archived. No new replies allowed.