What advantage (if any) is there to using typedef
in place of #define
in C code?
As an example, is there any advantage to using
typedef unsigned char UBYTE
over
#define UBYTE unsigned char
when both can be used as
void func()
{
UBYTE byte_value = 0;
/* Do some stuff */
return byte_value;
}
Obviously the pre-processor will try to expand a #define
wherever it sees one, which wouldn't happen with a typedef
, but that doesn't seem to me to be any particular advantage or disadvantage; I can't think of a situation where either use wouldn't result in a build error if there was a problem.
typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.
The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.
typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.
1) Probably the great advantage is a cleaner code. Usually abusing macros transforms the code in an unmaintainable mess, known as: 'macro soup'.
2) By using a typedef you define a new type. Using a macro you actually substitute text. The compiler is surely more helpful when dealing with typedef errors.
If you do a typedef of an array type, you'll see the difference:
typedef unsigned char UCARY[3];
struct example { UCARY x, y, z; };
Doing that with a #define... no, let's not go there.
[EDIT]: Another advantage is that a debuggers usually know about typedefs but not #defines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With