recently I found typedef in my code works really different than what I proposed. An example like this:
typedef int *ptype;
ptype v1 = 0, v2 = 0;
The result: both v1 and v2 were defined as a pointer to int type. But if you simply replace ptype by int * in the second sentence as int *v1 = 0, v2 = 0; or int* v1 = 0, v2 =0;, only v1 will be the pointer and v2 is normal int. It seems typedef does not do a simple replacement. What’s more, when it comes to complicate modifier like:
typedef int *ptype;
const ptype v3 = 0;
The result will be: v3 is a const pointer, not a pointer to the const int if we write const int *v3 = 0;. In the above code const stands as the modifier to the whole ptype, not the int inside ptype. Thus it really looks like typedef combines the compound type int* and creates a new type.
However, the authoritative C/C++ reference website cplusplus says “typedef does not create different types. It only creates synonyms of existing types.” so I was really confused and hope someone can help explain the behavior of typedef. Thanks!
“Synonym” does not mean “text replacement”.
ptypeis not literally expanded toint *by the preprocessor or anything.What it means is that you can do things like:
The assignment is valid because
ptypeandint *are the same type; there is no type conversion or cast required.typedefsimply lets you give a new name to an existing type. But that name combines every aspect of the existing type into an indivisible entity, such that e.g.ptype a, b;is equivalent toptype a; ptype b;(andconst ptypemeans “const pointer-to-int” becauseptypemeans “pointer-to-int”).In other words, the new names created by
typedefbehave like built-in keywords as far as declaring things goes, but the actual types represented by those names are the same.