typedef vs #define

Andrew P. Mullhaupt amull at Morgan.COM
Sun Feb 25 07:33:22 AEST 1990


In article <8430 at cbnewsh.ATT.COM>, em at cbnewsh.ATT.COM (edward.man) writes:
> 
> Is there any compiler writer out there? I have a C question that's
> best answered by C compiler writers. Of course other C experts
> can also provide insights and comments. However, I am looking for
> a sure answer. 
(Then make sure to check the info you get from the net with the
new ANSI standard).
>	The question is:
> 
> Consider the following two C statements:
> 	typedef short	FLAGS
> 	#define FLAGS	short
> 
> If I had two identical pieces of code, one used the "typedef" and
> ther other "#define" as defined above, would there be any difference
> in the compiled code? Does the C compiler handle the two differently?

If your code compiles, it shouldn't result in different object code,
although debugging information could conceivably be different. However,
the exposure to name conflicts of the two approches differs. The lexical
scope of the typedef is one matter, but the #define can be modified by
the #undef directive. 

> 
> I know "#define" is handled by cpp and the compiler never sees FLAGS.
> How is "typedef" handled, by cpp or the compiler?

The preprocessor doesn't process the typedef.

The easiest way to find out the difference here is to consider an
example with pointer types. If you will turn to page 146 in K&R2
you will find the following:

"In effect, typedef is like #define, except that since it is
interpreted by the compiler, it can cope with textual substitutions
that are beyond the capabilities of the preprocessor. For example,

	typedef int (*PFI)(char *, char *);

creates the type PFI, for 'pointer to function (of two char *
arguments) returning int,' which can be used in contexts like

	PFI strcmp, numcmp;

in the sort of program of Chapter 5."

Later,
Andrew Mullhaupt



More information about the Comp.lang.c mailing list