3
#define T Stack_T
typedef struct T *T;

Then what does T in struct T mean,the one defined by #define or typedef?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
compiler
  • 4,143
  • 9
  • 36
  • 40

4 Answers4

8

#define directives are substituted early on in the compilation process (translation phase 4, compilation doesn't actually occur until phase 7, these phases and what happens during them are detailed in the standard, section 5.1.1.2).

That #define will simply change T pre-processing tokens into Stack_T.

The effect of that on the typedef will be to turn it into:

typedef struct Stack_T *Stack_T;

Following that, Stack_T is defined as a type, a pointer to another type of struct Stack_T. The Stack_T and struct Stack_T are two separate things.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Then what does `Stack_T` in `struct Stack_T` mean after `typedef struct Stack_T *Stack_T; ` ? It looks like dead lock to me.. – compiler Mar 22 '11 at 09:59
  • No, there is a difference between the _type_ `Struct_T` and the _structure_ `struct Stack_T`. If it helps, you can think of them existing in two different "dictionaries" (for want of a better term). – paxdiablo Mar 22 '11 at 10:03
  • So you mean `Stack_T` in `struct Stack_T` doesn't have its own meaning(can't be interpreted recursively),this is weird,really. – compiler Mar 22 '11 at 10:05
  • `struct x` is a structure with the `x` tag. `x`, assuming it's been typedef'ed, is an actual type. They're distinct from each other so you can use the typedef to refer to a structure with the tag without clashing. – paxdiablo Mar 22 '11 at 10:11
  • As the C committee has always strived for needless syntax complexity, struct tags have their own unique local scope in C, which takes presedence over the scope where the struct is declared. Without that little oddity of a syntax rule, the code wouldn't work (I suspect it doesn't work in C++?). – Lundin Mar 22 '11 at 10:53
3

The preprocessor does only do text-substitutions, so that code would look like

typedef struct Stack_T *Stack_T;

So every T in your code is first replaced to Stack_T, and after that your compiler kicks in, sees the typedef and uses struct Stack_T*.

It might be good to know that struct Type and Type are only the same in C++, not in C.

filmor
  • 30,840
  • 6
  • 50
  • 48
0

Since #define is processed in pre-compilation and struct in compilation, after the pre-compilation you'll have typedef struct T *T; looks like that: typedef struct Stack_T *Stack_T;

MByD
  • 135,866
  • 28
  • 264
  • 277
0

The T represents Stack_T so, you can read the typedef as:

typdef struct Stack_T *Stack_T;

so every T in your code is replaced as Stack_T during compiler compilation.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228