Typedefs

What are typedefs?

A typedef is simply an alias (synonym) of the name of a variable type. Defining a typedef of a type makes it possible to refer to that type using the name of the typedef.

Defining a typedef

A typedef is defined by writing the keyword typedef followed by the name of the type we want to define an alias of, then the word we want to be the alias and finally a semicolon ;. Let us consider the primitive unsigned int long long (Which is actually equivalent to unsigned long long, because the int is optional here). The name of that type is very long. We could use a typedef to make the word ULL an alias of that type. We could then use the name ULL instead of unsigned long long, as they would be synonyms.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> typedef unsigned long long ULL; ULL add(ULL a, ULL b) { return a+b; } int main() { ULL num = add(7, 5); std::cout << num << std::endl; std::cout << sizeof(ULL) << std::endl; std::cout << sizeof(unsigned long long) << std::endl; return 0; }

Yes. It is that simple.

With structures

That is not the case in C++, but in C, in order to define a variable of a structure type, we must use the keyword struct before the name of the structure type. Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct Name { char* _firstName; char* _lastName; }; int main() { struct Name name; /* Note the keyword 'struct' here, which, in C only, is obligatory. In C++, we can omit it. */ return 0; }

It is possible to also avoid having to use the keyword struct, in C, by using typedefs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Name { char* _firstName; char* _lastName; }; typedef struct Name Name; int main() { Name name; // Now, 'Name' is a synonym of 'struct Name'. return 0; }

In the example above, the typedef is used to make Name an alias of struct Name.