to alias a type. Top google search results give me this definition for usage
typedef existing_type new_type
which cannot be more wrong due to its gross simplification to make things “easy” for people.
Take the following case:
typedef int (*fptr)(int x);What’s the existing type and the new type here? See the problem with gross simplifications. They are fine as long as they are not incorrect in their entirety.
typedef is simply
typedef declarationwhere declaration is same as any other declaration ( declarators and declaration can go very deep in semantics ), and a declaration involves both a type and a name, which is what typedef uses. Simple declarations can be broken down into the incorrect form above, though it fails quickly.
int x // can be
int* x // can be
int x[3] // cannot be
int f(int) // cannot be
int (*f)(int) // cannot beFor example, these are valid.
typedef int array3[3];
typedef int (*fptr)(int);A few gotchas
Can I redefine a typedef? Yes, as long as it’s the same it’s not a compile failure.
typedef int x;
typedef int x; // fine
typedef double x; // will not compile, same as how you can't to int x = 10; int x = 20;Can you undefine a typedef? No. You can get the desired effect with macro magic though.
Can you use typedefs recursively? Yes. This works.
typedef int array3[3];
typedef array3 array2x3[2];
int main() {
array2x3 a = {{1, 2, 3}, {4, 5, 6}};
}