typedef seems to be C++ specific (perhaps in some other languages). I find it hides the real data type of the value, thus is confusing someone new to the project. Perhaps it is useful to shorten the typing sometimes. When do you recommend the use of typedef?
I also notice I can’t pass a typedef-ed value to a function that accepts the underlying type?
something like:
typedef string VAL;
VAL s = "x";
func(string x); // if I try to pass `s`, I get something like no instance of function template match argument list
typedefis a C and C++ language label used to create a new type from an existing type. The best place is to use it with the C programming language with structs such as the following example or to use it to create a new, more abstract type from an existing primitive type (short, long, etc.).Before typedef was introduced into C, in order to use the above struct as a type you would have had to do something like the following:
In C++ structs and classes are similar constructs which create new types so the
typedefis not as useful for those types of variables. However if you are using a built in primitive type to represent some other, more abstract type then the typedef statement helps you to specify the type in a more abstract way.This use of
typedefmakes it a lot easier to specify a label for a type so that when a programmer is reading the source code they can understand what a particular variable represents. For instance if you have a color value variable that fits in anunsigned shortif you use atypedefto create a new type for color value and use it consistently then it is much easier to recognize that a variable contains a color value and not some other kind of anunsigned short.What
typedefalso allows is that it makes it much easier to find all of the places in the source where a particular abstract type is being used and it makes it easier to change the underlying type. For instance if your color value type starts off as a byte so you usetypedefto create an abstract type liketypedef unsigned char ColorValue;and then later you find that you need to change it from anunsigned charto anunsigned short, there would be a single place to make the change and if your use of the type was reasonably strict, that would be the only place you need to make a change.