• Home
  • 1.11 Type Aliases (using)

1.11 Type Aliases (using)

View Categories

1.11 Type Aliases (using)

< 1 min read

Table of Contents

The using keyword can also be used to create a type alias. It provides the same functionality as typedef but offers a more consistent syntax and is especially useful when working with templates.

This example demonstrates how to define and use a type alias with using.

Source Code #

#include <iostream>

using uint = unsigned int;

int main()
{
    uint student_count = 120;

    std::cout << "Student Count: " << student_count << '\n';

    return 0;
}

Output #

Student Count: 120

Explanation #

  • using uint = unsigned int; creates the alias uint for the existing type unsigned int.
  • The using keyword does not define a new data type. It only introduces another name for an existing type.
  • uint student_count = 120; is equivalent to writing unsigned int student_count = 120;.
  • Compared to typedef, the using syntax is easier to read because the alias name appears on the left side of the assignment.
  • using is the preferred approach for creating type aliases in modern C++ and also supports template aliases.
  • std::cout << "Student Count: " << student_count << '\n'; prints the value stored in the variable.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *