C/C++ Programming Practices – Typedefs and #defines

cprogramming practices

We all have definitely used typedefs and #defines 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:

#define MYINTEGER int

you could legally write:

short MYINTEGER x = 42;

because short MYINTEGER expands to short int.

On the other hand, with a typedef:

typedef int MYINTEGER:

the name MYINTEGER is another name for the type int, not a textual substitution for the keyword "int".

Things get even worse with more complicated types. For example, given this:

typedef char *char_ptr;
char_ptr a, b;
#define CHAR_PTR char*
CHAR_PTR c, d;

a, b, and c are all pointers, but d is a char, because the last line expands to:

char* c, d;

which is equivalent to

char *c;
char d;

(Typedefs for pointer types are usually not a good idea, but this illustrates the point.)

Another odd case:

#define DWORD long
DWORD double x;     /* Huh? */