We all have definitely used typedef
s and #define
s one time or the other. Today while working with them, I started pondering on a thing.
Consider the below 2 situations to use int
data type with another name:
typedef int MYINTEGER
and
#define MYINTEGER int
Like above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.
Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime).
Best Answer
A
typedef
is generally preferred unless there's some odd reason that you specifically need a macro.macros do textual substitution, which can do considerable violence to the semantics of the code. For example, given:
you could legally write:
because
short MYINTEGER
expands toshort int
.On the other hand, with a typedef:
the name
MYINTEGER
is another name for the typeint
, not a textual substitution for the keyword "int".Things get even worse with more complicated types. For example, given this:
a
,b
, andc
are all pointers, butd
is achar
, because the last line expands to:which is equivalent to
(Typedefs for pointer types are usually not a good idea, but this illustrates the point.)
Another odd case: