• Home
  • 1.17 Character Types

1.17 Character Types

View Categories

1.17 Character Types

1 min read

Table of Contents

C++ provides multiple character data types for storing characters of different sizes and encoding schemes. The char type is commonly used for ordinary characters, while other character types support larger character sets such as Unicode.

This example demonstrates the declaration and use of commonly used character data types.

Source Code #

#include <iostream>

int main()
{
    char letter = 'A';
    wchar_t wide_letter = L'A';
    char16_t utf16_letter = u'A';
    char32_t utf32_letter = U'A';

    std::cout << "char: " << letter << '\n';
    std::cout << "wchar_t size: " << sizeof(wchar_t) << " byte(s)\n";
    std::cout << "char16_t size: " << sizeof(char16_t) << " byte(s)\n";
    std::cout << "char32_t size: " << sizeof(char32_t) << " byte(s)\n";

    return 0;
}

Output #

char: A
wchar_t size: 4 byte(s)
char16_t size: 2 byte(s)
char32_t size: 4 byte(s)

The size of wchar_t is implementation-defined and may be 2 bytes or 4 bytes depending on the compiler and operating system.

Explanation #

  • char stores a single ordinary character and is typically used for ASCII text.
  • wchar_t is a wide character type intended to represent a larger character set than char.
  • char16_t stores a UTF-16 code unit and is primarily used for UTF-16 encoded text.
  • char32_t stores a UTF-32 code unit and can represent any Unicode code point directly.
  • The prefixes L, u, and U create wide, UTF-16, and UTF-32 character literals respectively.
  • sizeof is used to determine the storage size of each character type.
  • The exact size of wchar_t depends on the implementation, while 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 *