Why use C typedefs rather than #defines?
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 开发者_Python百科#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.
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.
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.
Well, coming from a C++, perspective, a C++ programmer using your code might have something like:
template<typename T> class String { typedef T char_type; // ... };
Now, if in your C code, you've written something like:
#define char_type uint32_t // because I'm using UTF-32
Well, you are going to be causing serious trouble for the users of your header file. With typedefs, you can change the value of the typedef within different scopes... while scopes aren't respected with #defines.
I know that you've labeled this C, but C programmers and C++ programmers need to realize that their headers might be used by each other... and this is one of those things to keep in mind.
With #define
all you get is string substitution during preprocessing. typedef
introduces a new type. This makes it easier to find possible problems in your code and in case of any the compiler might be able to give you more detailed information.
- Debuggers and compiler error messages become more helpful if the compiler/debugger knows about the type. (this is also why you should use constants and not defines where possible)
- Arrays, as others have shown
- you can restrict typedefs to a smaller scope (say, a function). Even more true in C++.
精彩评论