• Home
  • 1.18 Unicode Characters

1.18 Unicode Characters

View Categories

1.18 Unicode Characters

1 min read

Table of Contents

C++ supports Unicode character literals for representing characters beyond the ASCII character set. Unicode enables programs to store and process text from many languages using a standardized character encoding.

This example demonstrates how to declare Unicode character literals using char16_t and char32_t.

Source Code #

#include <iostream>

int main()
{
    char16_t symbol16 = u'Ω';
    char32_t symbol32 = U'😀';

    std::cout << "char16_t size: " << sizeof(symbol16) << " byte(s)\n";
    std::cout << "char32_t size: " << sizeof(symbol32) << " byte(s)\n";

    return 0;
}

Output #

char16_t size: 2 byte(s)
char32_t size: 4 byte(s)

Unicode characters are stored in the variables, but they are not printed in this example because std::cout does not directly support outputting char16_t and char32_t character values.

Explanation #

  • char16_t symbol16 = u'Ω'; declares a UTF-16 character and initializes it with the Unicode character Ω.
  • char32_t symbol32 = U'😀'; declares a UTF-32 character and initializes it with the Unicode character 😀.
  • The prefix u creates a UTF-16 character literal of type char16_t.
  • The prefix U creates a UTF-32 character literal of type char32_t.
  • sizeof(symbol16) returns the storage size of a UTF-16 code unit, which is 2 bytes.
  • sizeof(symbol32) returns the storage size of a UTF-32 code unit, which is 4 bytes.
  • Unicode support allows C++ programs to represent characters from many writing systems instead of being limited to the basic ASCII character set.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

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