what exactly is "typedef"?
Printable View
what exactly is "typedef"?
typedef define a type alias. It is a good solution for defining an otherwise long expression.
// typedef used for defining a function pointer.
typedef TypeBase (*TypeDefExample)(int x, char y, TypeClient z);
Kuphryn
You'll often see this:
Personally, I (generally) avoid typedef because it makes code harder to read. There are only a few actual types, and I don't like having to go find the typedef to find-out what the actual type is.Code:typedef unsigned long ULONG;
unsigned long X = 0; // This is the 'normal' way
ULONG Y = 0; // This requires typedef
I suppose it's OK when it's something more complicated like Kuphryn's pointer example. The <windows> header has lots (maybe hundreds) of typedefs. This means that there are several "different" Windows-defined "types" that are really the same types (pointers to long integers, etc.) The advantage of the Windows typedefs, is that the type provides some context, some hint about the purpose of the variable. The disadvantage is that you have to check the WinAPI documentation to find-out what the real type is.
Typedefs are useful for the following reasons.
1. To help with portability.
Very few types have the same size across all machines, and the standard only specifies a minimum size for things like char, short, int and long.
So you might say
to give you some idea of the range of a data type. Should you ever need to change it, then you only have one typedef to change instead of lots of 'unsigned short'.Code:typedef unsigned short UINT16;
2. To document meaning in your code
If you were working with lots of distance measurements say, then you could do
3. Complex declarationsCode:typedef double distance_t;
distance_t here, there, everywhere;
Function pointers (as shown by kuphryn) get very hairy very quicky. A typedef saves an awful lot of complex verbage in the code.