Are typedef and #define the same in c?

Viewed 75300

I wonder if typedef and #define are the same in ?

11 Answers

As mentioned above, there is a key difference between #define and typedef. The right way to think about that is to view a typedef as being a complete "encapsulated" type. It means that you cannot add to it after you have declared it.

You can extend a macro typename with other type specifiers, but not a typedef'd typename:

#define fruit int
unsigned fruit i;   // works fine

typedef int fruit;
unsigned fruit i;   // illegal

Also, a typedef'd name provides the type for every declator in a declaration.

#define fruit int *
fruit apple, banana;

After macro expansion, the second line becomes:

int *apple, banana;

Apple is a pointer to an int, while banana is an int. In comparison. a typedef like this:

typedef char *fruit;
fruit apple, banana;

declares both apple and banana to be the same. The name on the front is different, but they are both pointers to a char.

Another reason to use typedef (which has only been mentioned briefly in other answers and yet I think is the entire reason typedef was created) is to make debugging easier when using libraries that have custom types. For example, I'll use a type-conversion error. Both the codes below will print a compile-time error saying that a char is not comparable to a string, but in different ways.

typedef char letter;
letter el = 'e';
if(el == "hello");

The above code will print something like the variable "el" of type letter (aka "char") is not compatable with type "char*"

#define letter char
letter el = 'e';
if(el == "hello");

This code will instead print the variable "el" of type char is not compatable with type "char*"

This may seem silly because I'm defining "letter" as "char", but in more complex libraries this can be extremely confusing because pointers to objects like buttons, windows, sound servers, images, and lots of other things are defined as unsigned char *, which would only be debuggable as exactly that when using the #define method.

Related