Are there types bigger than long long int in C++?
![]()
No, but you can use libraries like GMP to handle bigger numbers.
Depending on what your need is, you could create your own struct to handle the data type:
Standards
Extended integer types are explicitly allowed by the C and C++ standards.
C++11
C++11 N3337 draft 3.9.1 «Fundamental types» paragraph 3 says:
There are five standard signed integer types : “signed char”, “short int”, “int”, “long int”, and “long long int”. In this list, each type provides at least as much storage as those preceding it in the list. There may also be implementation-defined extended signed integer types. The standard and extended signed integer types are collectively called signed integer types. Plain ints have the natural size suggested by the architecture of the execution environment the other signed integer types are provided to meet special needs.
You should also consider intmax_t , which 18.4.1 «Header synopsis» paragraph 2 says:
The header defines all functions, types, and macros the same as 7.18 in the C standard.
C99
C99 N1256 draft explicitly allows them at 6.2.5 «Types» paragraph 4:
There are five standard signed integer types, designated as signed char, short int, int, long int, and long long int. (These and other types may be designated in several additional ways, as described in 6.7.2.) There may also be implementation-defined extended signed integer types.28) The standard and extended signed integer types are collectively called signed integer types.29)
and 7.18.1.5 «Greatest-width integer types» paragraph 1 says:
The following type designates a signed integer type capable of representing any value of any signed integer type:
intmax_t
Вся правда о целочисленных типах в C
Если вы уверенно сможете правильно ответить на эти вопросы, тогда эта статья не для вас. В противном случае десять минут, потраченные на её чтение, будут весьма полезны.
- Знаковые оба.
- Законны оба.
- 8.
- 2147483647. -2147483648.
- Конечно, Кэп.
- char — не регламентируется, int — знаковый.
- Для int — законно, а для char — нет.
- Не менее 8.
- 32767. -32767
- Вообще говоря, нет.
Про signed и unsigned
Все целочисленные типы кроме char , по умолчанию знаковые (signed).
С char ситуация сложнее. Стандарт устанавливает три различных типа: char , signed char , unsigned char . В частности, указатель типа (signed char *) не может быть неявно приведён к типу (char *) .
Хотя формально это три разных типа, но фактически char эквивалентен либо signed char , либо unsigned char — на выбор компилятора (стандарт ничего конкретного не требует).
Подробнее про char я написал в комментариях.
О размере unsigned char
Тип unsigned char является абстракцией машинного байта. Важность этого типа проявляется в том, что С может адресовать память только с точностью до байта. На большинстве архитектур размер байта равен 8 бит, но бывают и исключения. Например, процессоры с 36-битной архитектурой как правило имеют 9-битный байт, а в некоторых DSP от Texas Instruments байты состоят из 16 или 32 бит. Древние архитектуры могут иметь короткие байты из 4, 5 или 7 бит.
Стандарт С вынужден отказаться от допотопных архитектур и требует, чтобы байты были как минимум 8-битные. Конкретное значение ( CHAR_BIT 2) ) для данной платформы записано в заголовочном файле limits.h .
Размеры целочисленных типов в С
C переносимый, поэтому в нём базовые целочисленные типы ( char , short , int и др.) не имеют строго установленного размера, а зависят от платформы. Однако эти типы не были бы переносимы, если бы
их размеры были совершенно произвольные: стандарт устанавливает минимальные диапазоны принимаемых значений для всех базовых целочисленные типов. А именно,
- signed char: -127. 127 (не -128. 127; аналогично другие типы)
- unsigned char : 0. 255 (= 2 8 −1)
- signed short : -32767. 32767
- unsigned short : 0. 65535 (= 2 16 −1)
- signed int : -32767. 32767
- unsigned int : 0. 65535 (= 2 16 −1)
- signed long : -2147483647. 2147483647
- unsigned long : 0. 4294967295 (= 2 32 −1)
- signed long long : -9223372036854775807. 9223372036854775807
- unsigned long long : 0. 18446744073709551615 (= 2 64 −1)
Стандарт требует sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long) . Таким образом, вполне законны ситуации типа sizeof(char)=sizeof(long)=32 . Для некоторых DSP от Texas Instruments так и есть.
Конкретные значения этих диапазонов для данной платформы указаны заголовочном файле limits.h .
Новые типы в С99
После того, как C99 добавил тип long long , целочисленных типов и путаницы стало ещё больше. Чтобы навести порядок, стандарт ввёл заголовочный файл stdint.h , где определяются типы вроде int16_t (равно 16 бит), int_least16_t (минимальный тип, способный вместить 16 бит), int_fast16_t (по крайней мере 16 бит, работа с этим типом наиболее быстрая на данной платформе) и т. п.
least- и fast-типы фактически являются заменой рассмотренных выше типов int , short , long и т. п. только вдобавок дают программисту возможность выбора между скоростью и размером.
От типов вроде int16_t , со строгим указанием размера, страдает переносимость: скажем, на архитектуре с 9-битным байтом может просто не найтись 16-битного регистра. Поэтому стандарт тут явно говорит, что эти типы опциональны. Но учитывая, что какой бы код вы ни писали, чуть менее чем во всех случаях целевая архитектура фиксирована даже в худшем случае с точностью до семейства (скажем, x86 или AVR), внутри которого, размер байта не может вдруг поменяться, то переносимость фактически сохраняется. Более того, типы вроде int16_t оказались даже более популярными, чем int_least16_t и int_fast16_t , а при низкоуровневом программировании (микроконтроллеры, драйверы устройств) и подавно, ибо там зачастую неопределённость размера переменной просто непозволительна.
1) Для удобства тройку архитектура+ОС+компилятор далее будем называть просто платформой.
2) Этот макрос правильнее было бы назвать UCHAR_BIT , но по причинам совместимости он называется так, как называется.
Что больше long long c
All variables use data type during declarations to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data it can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Different data types require a different amount of memory.
Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647.
Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold.
Below is a list of ranges along with the memory requirements and format specifiers on the 32-bit GCC compiler.
S. No.
Data Type
Memory
(bytes)
Range
Long long takes the double memory as compared to long. But it can also be different on various systems. Its range depends on the type of application. The guaranteed minimum usable bit sizes for different data types:
- char: 8
- short:16
- int: 16
- long: 32
- long long: 64
The decreasing order is: long long >=long>=int>=short>=char
Program 1:
In various competitive coding platforms, the constraints are between 10 7 to 10 18 . Below is the program to understand the concept:
Name already in use
cpp-docs / docs / cpp / fundamental-types-cpp.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
32 contributors
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Built-in types (C++)
Built-in types (also called fundamental types) are specified by the C++ language standard and are built into the compiler. Built-in types aren’t defined in any header file. Built-in types are divided into three main categories: integral, floating-point, and void. Integral types represent whole numbers. Floating-point types can specify values that may have fractional parts. Most built-in types are treated as distinct types by the compiler. However, some types are synonyms, or treated as equivalent types by the compiler.
The void type describes an empty set of values. No variable of type void can be specified. The void type is used primarily to declare functions that return no values or to declare generic pointers to untyped or arbitrarily typed data. Any expression can be explicitly converted or cast to type void . However, such expressions are restricted to the following uses:
An expression statement. (For more information, see Expressions.)
The left operand of the comma operator. (For more information, see Comma Operator.)
The second or third operand of the conditional operator ( ? : ). (For more information, see Expressions with the Conditional Operator.)
The keyword nullptr is a null-pointer constant of type std::nullptr_t , which is convertible to any raw pointer type. For more information, see nullptr .
The bool type can have values true and false . The size of the bool type is implementation-specific. See Sizes of built-in types for Microsoft-specific implementation details.
The char type is a character representation type that efficiently encodes members of the basic execution character set. The C++ compiler treats variables of type char , signed char , and unsigned char as having different types.
Microsoft-specific: Variables of type char are promoted to int as if from type signed char by default, unless the /J compilation option is used. In this case, they’re treated as type unsigned char and are promoted to int without sign extension.
A variable of type wchar_t is a wide-character or multibyte character type. Use the L prefix before a character or string literal to specify the wide-character type.
Microsoft-specific: By default, wchar_t is a native type, but you can use /Zc:wchar_t- to make wchar_t a typedef for unsigned short . The __wchar_t type is a Microsoft-specific synonym for the native wchar_t type.
The char8_t type is used for UTF-8 character representation. It has the same representation as unsigned char , but is treated as a distinct type by the compiler. The char8_t type is new in C++20. Microsoft-specific: use of char8_t requires the /std:c++20 compiler option or later (such as /std:c++latest ).
The char16_t type is used for UTF-16 character representation. It must be large enough to represent any UTF-16 code unit. It’s treated as a distinct type by the compiler.
The char32_t type is used for UTF-32 character representation. It must be large enough to represent any UTF-32 code unit. It’s treated as a distinct type by the compiler.
Floating-point types use an IEEE-754 representation to provide an approximation of fractional values over a wide range of magnitudes. The following table lists the floating-point types in C++ and the comparative restrictions on floating-point type sizes. These restrictions are mandated by the C++ standard and are independent of the Microsoft implementation. The absolute size of built-in floating-point types isn’t specified in the standard.
| Type | Contents |
|---|---|
| float | Type float is the smallest floating point type in C++. |
| double | Type double is a floating point type that is larger than or equal to type float , but shorter than or equal to the size of type long double . |
| long double | Type long double is a floating point type that is larger than or equal to type double . |
Microsoft-specific: The representation of long double and double is identical. However, long double and double are treated as distinct types by the compiler. The Microsoft C++ compiler uses the 4- and 8-byte IEEE-754 floating-point representations. For more information, see IEEE floating-point representation.
The int type is the default basic integer type. It can represent all of the whole numbers over an implementation-specific range.
A signed integer representation is one that can hold both positive and negative values. It’s used by default, or when the signed modifier keyword is present. The unsigned modifier keyword specifies an unsigned representation that can only hold non-negative values.
A size modifier specifies the width in bits of the integer representation used. The language supports short , long , and long long modifiers. A short type must be at least 16 bits wide. A long type must be at least 32 bits wide. A long long type must be at least 64 bits wide. The standard specifies a size relationship between the integral types:
1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)
An implementation must maintain both the minimum size requirements and the size relationship for each type. However, the actual sizes can and do vary between implementations. See Sizes of built-in types for Microsoft-specific implementation details.
The int keyword may be omitted when signed , unsigned , or size modifiers are specified. The modifiers and int type, if present, may appear in any order. For example, short unsigned and unsigned int short refer to the same type.
Integer type synonyms
The following groups of types are considered synonyms by the compiler:
short , short int , signed short , signed short int
unsigned short , unsigned short int
int , signed , signed int
unsigned , unsigned int
long , long int , signed long , signed long int
unsigned long , unsigned long int
long long , long long int , signed long long , signed long long int
unsigned long long , unsigned long long int
Microsoft-specific integer types include the specific-width __int8 , __int16 , __int32 , and __int64 types. These types may use the signed and unsigned modifiers. The __int8 data type is synonymous with type char , __int16 is synonymous with type short , __int32 is synonymous with type int , and __int64 is synonymous with type long long .
Sizes of built-in types
Most built-in types have implementation-defined sizes. The following table lists the amount of storage required for built-in types in Microsoft C++. In particular, long is 4 bytes even on 64-bit operating systems.