Press "Enter" to skip to content

Name already in use

Optional single quotes ( ‘ ) may be inserted between the digits as a separator; they are ignored during compilation.

Escape-последовательность

Сочетания символов, состоящие из обратной косой черты (\), за которой следует буква или сочетание цифр, называются escape-последовательностями. Для представления символа новой строки, одинарной кавычки или некоторых других символов в символьной константе необходимо использовать escape-последовательности. Escape-последовательность рассматривается как один символ и, следовательно, является допустимой символьной константой.

Escape-последовательности обычно используются для указания действий, например возврата каретки или табуляции, на терминалах и принтерах. Они также используются для обозначения буквенных представлений непечатаемых символов, а также символов, которые обычно имеют специальное значение, например двойных кавычек ( ). В следующей таблице перечислены escape-последовательности ANSI и представляемые ими значения.

Обратите внимание, что вопросительный знак, перед которым стоит обратная косая черта (\?), обозначает литерал вопросительного знака в случаях, когда эта последовательность символов может быть ошибочно интерпретирована как триграф. Дополнительные сведения см. в разделе Триграфы.

Escape-последовательность

Escape-последовательность Представляет
\a Звонок (предупреждение)
\b Backspace
\f Перевод страницы
\n Новая строка
\r Возврат каретки
\t Горизонтальная табуляция
\v Вертикальная табуляция
\’ Одиночная кавычка
\” Двойная кавычка
\\ Обратная косая черта
\? Литерал вопросительного знака
\ooo Символ ASCII в восьмеричной нотации
\xhh Символ ASCII в шестнадцатеричной нотации
\xhhhh Символ юникода в шестнадцатеричном формате, если эта escape-последовательность используется в многобайтовой знаковой константе или строковом литерале юникода.

Блок, относящийся только к системам Microsoft

Если обратная косая черта предшествует символу, которого нет в таблице, компилятор не обрабатывает неопределенный символ сам как символ. Например, escape-последовательность \c обрабатывается как символ c .

Завершение блока, относящегося только к системам Майкрософт

Escape-последовательности позволяют отправлять неграфические управляющие символы на устройство отображения. Например, символ ESC ( \033) часто используется в качестве первого символа команды управления для терминала или принтера. Некоторые escape-последовательности используются только на конкретных устройствах. Например, escape-последовательности вертикальной табуляции и перевода страницы ( \v и \f) не влияют на вывод данных на экране, но отвечают за соответствующие операции на принтере.

Кроме того, обратную косую черту ( \ ) можно использовать как символ продолжения. Если сразу за обратной косой чертой следует символ новой строки (эквивалентен нажатию клавиши ВОЗВРАТ), компилятор игнорирует эту последовательность и обрабатывает следующую строку как продолжение предыдущей. Эта возможность используется в основном для определений препроцессора, длина которых превышает одну строку. Пример:

#define assert(exp) \ ( (exp) ? (void) 0:_assert( #exp, __FILE__, __LINE__ ) ) 

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Cancel Create

cpp-docs / docs / cpp / fundamental-types-cpp.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Latest commit 6534890 Aug 17, 2021
* fix code sample (#3676) * fix code sample * acrolinx Co-authored-by: TylerMSFT * Address 3269 typo in warning number (#3680) * Fixed typo: evalution –> evaluation * Fixed typo: evalution –> evaluation * Bulk Fix – Sentence form for all alt text (#3683) * Updated C/C++ workload name The workload for C/C++ development in VS Build Tools 2019 installer is called ‘Desktop development with C++’. * Split out docs by version Add VS2017-specific instructions. * Updated C/C++ workload name The workload for C/C++ development in VS Build Tools 2019 installer is called ‘Desktop development with C++’. * Split out docs by version Add VS2017-specific instructions. * Add 16.11 Compiler Warnings C5247 and C5248 (#3689) * Add C5247 and C5248 * Fix link typos * Updates per Xiang Fan review * More wordsmithage * More fix per X.F. * Fix inconsistencies in CMake docs (#3692) * Standard format for CMake docs * Fix markdownlint * More cleanup. * Clean up link issue, acrolinx * Fix more broken things * Undo a change * Add documentation for “unspecified” architecture Add documentation regarding “unspecified” architecture such that it provides an option for someone to ensure that no inherited environment is selected. * Update markdownlint.json file for unordered lists (#3694) Block rule that wants * instead of – to prefix unordered lists, since we’ve standardized on the latter. Merging on my own recognizance as repo admin. * Clean up documentation for “unspecified” architecture * Markdown quality fixes 1 of N * Markdown quality fixes 2 of N * Markdown quality fixes 3 of N * Markdown quality fixes 4 of N * Markdown quality fixes 5 of N * Markdown quality fixes 6 of N * Markdown quality fixes 7 of N * Markdown quality fixes 8 of N * Markdown quality fixes 9 of N * Markdown quality fixes 10 of N * Undo TN038 * Markdown quality fixes 11 of N * Setting PATH allows DUMPBIN to be executed from the system command prompt. There are multiple DUMPBIN.EXE’s in the MSVC folder, but they can be executed if the PATH is set correctly. If this is not true, or undesireable per system design constraints, please clarify otherwise. * Call out toolchains and embedded scenarios * Add link to environment setting instructions * Make more readable * Address cpp-docs 3286 Postfix increment, decrement syntax (#3711) * Address cpp-docs issue 3286 * Fix formatting, final example * Add compiler warning C5243, C5249, C5250 (#3710) * Removing linux and non-windows bullet point * Make clear it’s not required to meet all conditions Add “or” to final bullet point * PR review edit, Microsoft style for lists * Make the “unspecified” architecture option more general * Add __SANITIZE_ADDRESS__ to predefined macros page Noticed __SANITIZE_ADDRESS__ was missing from this list. * Add VS version Also note the VS version where __SANITIZE_ADDRESS__ was added in. * Add docs on using existing cache without cmake-server * Fix unescaped (#3715) Noticed this while doing other changes. Without being in a code block, becomes the html element of the same name. * Address issue 3301 * Create and integrate /Zc:lambda article (#3719) * Create and integrate /Zc:lambda article * Fix conformance topic date * First half of C++20 changes * The other half of the /std:c++20 fixes * Fix link * Update cmake-projects-in-visual-studio.md * Remove duplicate line in build TOC * Cleanup per review Co-authored-by: Colin Robertson Co-authored-by: opbld15 Co-authored-by: Tyler Whitney Co-authored-by: TylerMSFT Co-authored-by: opbld17 Co-authored-by: ystamant Co-authored-by: opbld16 Co-authored-by: Andrew Shymanel Co-authored-by: Garrett Campbell Co-authored-by: PRMerger6 Co-authored-by: PRMerger12 Co-authored-by: PRMerger14 Co-authored-by: PRMerger16 Co-authored-by: PRMerger15 Co-authored-by: PRMerger7 Co-authored-by: PRMerger10 Co-authored-by: David Dyck Co-authored-by: Kristine Toliver Co-authored-by: Steve Wishnousky Co-authored-by: Sam Freed Co-authored-by: Don Spencer Co-authored-by: Beau Braig Co-authored-by: Paula Miller

32 contributors

Integer literal

Allows values of integer type to be used in expressions directly.

Contents

[edit] Syntax

An integer literal has the form

decimal-literal integer-suffix (optional) (1)
octal-literal integer-suffix (optional) (2)
hex-literal integer-suffix (optional) (3)
binary-literal integer-suffix (optional) (4) (since C++14)
  • decimal-literal is a non-zero decimal digit ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ), followed by zero or more decimal digits ( 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 )
  • octal-literal is the digit zero ( 0 ) followed by zero or more octal digits ( 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 )
  • hex-literal is the character sequence 0x or the character sequence 0X followed by one or more hexadecimal digits ( 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , a , A , b , B , c , C , d , D , e , E , f , F )
  • binary-literal is the character sequence 0b or the character sequence 0B followed by one or more binary digits ( 0 , 1 )
  • integer-suffix , if provided, may contain one or both of the following (if both are provided, they may appear in any order:
  • unsigned-suffix (the character u or the character U )
  • one of
  • long-suffix (the character l or the character L )
  • long-long-suffix (the character sequence ll or the character sequence LL )
  • size-suffix (the character z or the character Z )

Optional single quotes ( ‘ ) may be inserted between the digits as a separator; they are ignored during compilation.

An integer literal (as any literal) is a primary expression.

[edit] Explanation

1) Decimal integer literal (base 10)
2) Octal integer literal (base 8)

3) Hexadecimal integer literal (base 16, the letters ‘a’ through ‘f’ represent values (decimal) 10 through 15)

4) Binary integer literal (base 2)

The first digit of an integer literal is the most significant.

Example. The following variables are initialized to the same value:

int d = 42; int o = 052; int x = 0x2a; int X = 0X2A; int b = 0b101010; // C++14

Example. The following variables are also initialized to the same value:

unsigned long long l1 = 18446744073709550592ull; // C++11 unsigned long long l2 = 18'446'744'073'709'550'592llu; // C++14 unsigned long long l3 = 1844'6744'0737'0955'0592uLL; // C++14 unsigned long long l4 = 184467'440737'0'95505'92LLU; // C++14

[edit] The type of the literal

The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used:

  • int
  • long int
  • long long int (since C++11)
  • int
  • unsigned int
  • long int
  • unsigned long int
  • long long int (since C++11)
  • unsigned long long int (since C++11)
  • unsigned int
  • unsigned long int
  • unsigned long long int (since C++11)
  • unsigned int
  • unsigned long int
  • unsigned long long int (since C++11)
  • long int
  • unsigned long int (until C++11)
  • long long int (since C++11)
  • long int
  • unsigned long int
  • long long int (since C++11)
  • unsigned long long int (since C++11)
  • unsigned long int
  • unsigned long long int (since C++11)
  • unsigned long int
  • unsigned long long int (since C++11)
  • long long int (since C++11)
  • long long int (since C++11)
  • unsigned long long int (since C++11)
  • unsigned long long int (since C++11)
  • unsigned long long int (since C++11)
  • the signed version of std::size_t (since C++23)
  • the signed version of std::size_t (since C++23)
  • std::size_t (since C++23)
  • std::size_t (since C++23)
  • std::size_t (since C++23)

If the value of the integer literal is too big to fit in any of the types allowed by suffix/base combination and the compiler supports extended integer types (such as __int128 ) the literal may be given the extended integer type — otherwise the program is ill-formed.

[edit] Notes

Letters in the integer literals are case-insensitive: 0xDeAdBeEfU and 0XdeadBEEFu represent the same number (one exception is the long-long-suffix , which is either ll or LL , never lL or Ll ) (since C++11)

There are no negative integer literals. Expressions such as – 1 apply the unary minus operator to the value represented by the literal, which may involve implicit type conversions.

In C prior to C99 (but not in C++), unsuffixed decimal values that do not fit in long int are allowed to have the type unsigned long int .

When used in a controlling expression of #if or #elif, all signed integer constants act as if they have type std::intmax_t and all unsigned integer constants act as if they have type std::uintmax_t .

Due to maximal munch, hexadecimal integer literals ending in e and E , when followed by the operators + or – , must be separated from the operator with whitespace or parentheses in the source:

auto x = 0xE+2.0; // error auto y = 0xa+2.0; // OK auto z = 0xE +2.0; // OK auto q = (0xE)+2.0; // OK

Otherwise, a single invalid preprocessing number token is formed, which causes further analysis to fail.

Feature-test macro Value Std Comment
__cpp_binary_literals 201304L (C++14) Binary literals
__cpp_size_t_suffix 202011L (C++23) Literal suffixes for std::size_t and its signed version

[edit] Example

Run this code

#include #include #include int main() { std::cout  123  '\n'  0123  '\n'  0x123  '\n'  0b10  '\n'  12345678901234567890ull  '\n'  12345678901234567890u  '\n'; // the type is unsigned long long // even without a long long suffix // std::cout // 9223372036854775808 cannot fit in signed long long, which is the // biggest type allowed for unsuffixed decimal integer literal std::cout  -9223372036854775808u  '\n'; // unary minus applied to unsigned // value subtracts it from 2^64, this gives 9223372036854775808 std::cout  -9223372036854775807 - 1  '\n'; // correct way to calculate // the value -9223372036854775808 #if __cpp_size_t_suffix >= 202011L // C++23 static_assert(std::is_same_vdecltype(0UZ), std::size_t>); static_assert(std::is_same_vdecltype(0Z), std::make_signed_tstd::size_t>>); #endif }
123 83 291 2 12345678901234567890 12345678901234567890 9223372036854775808 -9223372036854775808

Comments are closed, but trackbacks and pingbacks are open.