• Home
  • 1.22 Wide Character Types

1.22 Wide Character Types

View Categories

1.22 Wide Character Types

1 min read

Table of Contents

C++ provides wide character types for representing characters that require more storage than the traditional char type. These types are primarily intended to support larger character sets and platform-specific character encodings.

The language defines wchar_t as a built-in type for wide characters. In addition, C++11 introduced char16_t and char32_t to represent UTF-16 and UTF-32 code units, respectively. These types provide more consistent support for Unicode text across different platforms.

Source Code #

#include <iostream>

int main()
{
    std::wcout << L"Wide Character: " << L'A' << '\n';

    std::cout << "Size of wchar_t : " << sizeof(wchar_t) << " bytes\n";
    std::cout << "Size of char16_t: " << sizeof(char16_t) << " bytes\n";
    std::cout << "Size of char32_t: " << sizeof(char32_t) << " bytes\n";

    return 0;
}

Output #

Wide Character: A
Size of wchar_t : 2 bytes
Size of char16_t: 2 bytes
Size of char32_t: 4 bytes

Note: The size of wchar_t is implementation-dependent. On many Windows systems it is 2 bytes, while on many Linux systems it is 4 bytes.

Explanation #

  • wchar_t is a built-in type used to store wide characters.
  • char16_t stores UTF-16 code units and always occupies 2 bytes.
  • char32_t stores UTF-32 code units and always occupies 4 bytes.
  • std::wcout is the standard output stream used for wide characters and wide strings.
  • The prefix L before a character or string literal creates a wide-character literal.
  • The sizeof operator returns the storage size of each character type in bytes.
  • The size of wchar_t depends on the compiler and operating system, whereas char16_t and char32_t have fixed sizes defined by the C++ standard.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

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