8.6 — Typedefs and type aliases

The typedef keyword

In C++, typedef (which is short for “type definition”) is a keyword that creates an alias for an existing data type. To create such an alias, we use the typedef keyword, followed by an existing data type to alias, followed by a name for the alias. For example:

By convention, typedef names typically use a “_t” suffix. This both indicates that the name is a typedef, and helps prevent naming collisions with other types of identifiers.

Best practice

Name your typedefs with a _t suffix, to indicate that the name is a typedef and help prevent naming collisions with other types of identifiers.

Once defined, a typedef name can be used anywhere a type is needed. For example, we can create a variable with the typedef name as the type:


When the compiler encounters a typedef name, it will substitute in the aliased type. For example:

This prints:


In the above program, we first define typedef distance_t as an alias for type double.

Next, we define a variable named milesToDestination of type distance_t. Because the compiler knows distance_t is a typedef, it will use the aliased type, which is double. Thus, variable milesToDestination is actually compiled to be a variable of type double, and it will behave as a double in all regards.

Finally, we print the value of milesToDestination, which prints as a double value.

Typedefs are not new types

A typedef does not actually define a new type -- it just introduces a new identifier for an existing type. A typedef is completely interchangeable with the aliased type.

This allows us to do things that are syntactically valid but semantically meaningless. For example:

Although conceptually we intend miles_t and speed_t to have distinct meanings, both are just typedefs for type long. This effectively means values of type miles_t, speed_t, and long can all be used interchangeably. And indeed, when we assign a value of type speed_t to a variable of type miles_t, the compiler only sees that we’re assigning a value of type long to a variable of type long, and it will not complain.


Care must be taken not to mix values of typedefs that are intended to be semantically distinct.

As an aside...

Some languages support the concept of a strong typedef. A strong typedef actually creates a new type that has all the original properties of the original type, but the compiler will throw an error if you try to mix values of the aliased type and the strong typedef. As of C++20, C++ does not directly support strong typedefs (though enum classes, covered in lesson 8.3 -- Scoped enumerations (enum classes), are similar), but there are quite a few 3rd party C++ libraries that implement strong typedef-like behavior.

The scope of typedefs

Because scope is a property of an identifier, typedef identifiers follow the same scoping rules as variable identifiers: a typedef defined inside a block has block scope and is usable only within that block, whereas a typedef defined in the global namespace has file scope and is usable to the end of the file. In the above example, miles_t and speed_t are only usable in the main() function.

If you need to use one or more typedefs across multiple files, they can be defined in a header file and #included into any code files that needs to use the definition:


Typedefs #included this way will be imported into the global namespace and thus have global scope.

Typedef issues

Typedefs have a few syntactical issues. First, it’s easy to forget whether the type name or type definition come first. Which is correct?

It’s easy to get backwards. Fortunately, in such cases, the compiler will complain.

Second, the syntax for typedefs can get ugly with more complex types. For example:

In the above typedef definition, the name of the new type (fcn_t) is buried in the middle of the definition, making the definition hard to read.

Type aliases

To help address the above-mentioned syntactical issues, an improved syntax for defining typedefs was introduced, called a type alias.

Given the following typedef:

The equivalent type alias syntax looks like this:

Type aliases are functionally equivalent to typedefs, but come with the benefit of a nicer definition syntax.

Here is the hard-to-read typedef we introduced above, along with an equivalent (and slightly easier to read) type alias:

Best practice

When creating aliased types, prefer the type alias syntax over the typedef syntax.

When should we use type aliases?

Now that we’ve covered what typedefs and type aliases are, let’s talk about what they are useful for.

Using type aliases for platform independent coding

One of the main use for type aliases is that they can be used to hide platform specific details. On some platforms, an int is 2 bytes, and on others, it is 4 bytes. Thus, using int to store more than 2 bytes of information can be potentially dangerous when writing platform independent code.

Because char, short, int, and long give no indication of their size, it is fairly common for cross-platform programs to use type aliases to define aliases that include the type’s size in bits. For example, int8_t would be an 8-bit signed integer, int16_t a 16-bit signed integer, and int32_t a 32-bit signed integer. Using type aliases in this manner helps prevent mistakes and makes it more clear about what kind of assumptions have been made about the size of the variable.

In order to make sure each aliased type resolves to a type of the right size, type aliases of this kind are typically used in conjunction with preprocessor directives:

On machines where integers are only 2 bytes, INT_2_BYTES can be #defined, and the program will be compiled with the top set of type aliases. On machines where integers are 4 bytes, leaving INT_2_BYTES undefined will cause the bottom set of type aliases to be used. In this way, int8_t will resolve to a 1 byte integer, int16_t will resolve to a 2 bytes integer, and int32_t will resolve to a 4 byte integer using the combination of char, short, int, and long that is appropriate for the machine the program is being compiled on.

The fixed-width integers (such as std::int_fast16_t and std::int_least32_t) and size_t type (both covered in lesson 4.6 -- Fixed-width integers and size_t) are actually just type aliases to various fundamental types.

This is also why when you print an 8-bit fixed-width integer using std::cout, you’re likely to get a character value. For example:

This program prints:


Because std::int_least8_t is typically defined as a type alias for one of the char types, variable x will be defined as a char type. And char types print their values as ASCII characters rather than as integer values.

Using type aliases to make complex types simple

Although we have only dealt with simple data types so far, in advanced C++, types can get complicated and lengthy to type. For example, you might see a function and variable defined like this:

Typing std::vector<std::pair<std::string, int> > everywhere you need to use that type is cumbersome and easy to typo. It’s much easier to use a type alias:

Much better! Now we only have to type pairlist_t instead of std::vector<std::pair<std::string, int> >.

Don’t worry if you don’t know what std::vector, std::pair, or all these crazy angle brackets are yet. The only thing you really need to understand here is that type aliases allow you to take complex types and give them a simple name, which makes your code easier to read and saves typing.

This is probably the best use for type aliases.

Using type aliases for legibility

Type aliases can also help with code documentation and comprehension.

With variables, we have the variable’s identifier to help document the purpose of the variable. But consider the case of a function’s return value. Data types such as char, int, long, double, and bool are good for describing what type a function returns, but more often we want to know what purpose a return value serves.

For example, given the following function:

We can see that the return value is an integer, but what does the integer mean? A letter grade? The number of questions missed? The student’s ID number? An error code? Who knows! The return type of int does not tell us much. If we’re lucky, documentation for the function exists somewhere that we can reference. If we’re unlucky, we have to read the code and infer the purpose.

Now let’s do an equivalent version using a type alias:

The return type of testScore_t makes it a little more obvious that the function is returning a type that represents a test score.

In our experience, creating a type alias just to document the return type of a single function isn’t worth it (use a comment instead). But if you have already created a typedef for other reasons, this can be a nice additional benefit.

Using type aliases for easier code maintenance

Type aliases also allow you to change the underlying type of an object without having to change lots of code. For example, if you were using a short to hold a student’s ID number, but then later decided you needed a long instead, you’d have to comb through lots of code and replace short with long. It would probably be difficult to figure out which objects of type short were being used to hold ID numbers and which were being used for other purposes.

However, if you use type aliases, then changing types becomes as simple as updating the type alias (e.g. from using studentID_t = short; to using studentID_t = long;).

While this seems like a nice benefit, caution is necessary whenever a type is changed, as the behavior of the program may also change. This is especially true when changing the type of a type alias to a type in a different type family (e.g. an integer to a floating point value, or vice versa)! The new type may have comparison or integer/floating point division issues, or other issues that the old type did not. If you change an existing type to some other type, your code should be thoroughly retested.

Downsides and conclusion

While type aliases offer some benefits, they also introduce yet another identifier into your code that needs to be understood. If this isn’t offset by some benefit to readability or comprehension, then the type alias is doing more harm than good.

A poorly utilized type alias can take a familiar type (such as std::string) and hide it behind a custom name that needs to be looked up. In some cases (such as with smart pointers, which we’ll cover in a future chapter), obscuring the type information can also be harmful to understanding how the type should be expected to work.

For this reason, type aliases should be used primarily in cases where there is a clear benefit to code readability or code maintenance. This is as much of an art as a science. Type aliases are most useful when they can be used in many places throughout your code, rather than in fewer places.

Best practice

Use type aliases judiciously, when they provide a clear benefit to code readability or code maintenance.

Quiz time

Question #1

Given the following function prototype:

Convert the int return value to a type alias named error_t. Include both the type alias statement and the updated function prototype.

Show Solution

8.7 -- Type deduction for objects using the auto keyword
8.5 -- Explicit type conversion (casting)

23 comments to 8.6 — Typedefs and type aliases

  • anvekar

    In this where exactly is INT_2_BYTES defined? It can't be in our program as we are unaware of the size of integer in any specific system.

    • Alex

      You'd have to define it in your program, somewhere above this point (or define it as a compiler flag as part of your project).

      How to determine whether integers are 2 bytes or not as part of the preprocessing phase is more complicated (but there are ways to do so, otherwise libraries like pstdint.h couldn't exist.

  • Todd


    "A typedef does not define (a) new type."

  • DanielN91


    I want to thank you for these tutorials. They are extremely helpful, concise and clear. I've been helped by them in many ways and every time I read them it seems like I'm learning something simple. I'm grateful for people like you, who want to share what they know and know how to do it.

    Keep up the good work! :)

    Learning from you,

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">