Int c что это

от admin

Int c что это

Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. It specifies the type of data that the variable can store like integer, character, floating, double, etc. The data type is a collection of data with values having fixed values, meaning as well as its characteristics.

The data types in C can be classified as follows:

Types Description
Primitive Data Types Arithmetic types can be further classified into integer and floating data types.
Void Types The data type has no value or operator and it does not provide a result to its caller. But void comes under Primitive data types.
User Defined DataTypes It is mainly used to assign names to integral constants, which make a program easy to read and maintain
Derived types The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types.

Different data types also have different ranges up to which they can store numbers. These ranges may vary from compiler to compiler. Below is a list of ranges along with the memory requirement and format specifiers on the 32-bit GCC compiler.

Data Type Memory (bytes) Range Format Specifier
short int 2 -32,768 to 32,767 %hd
unsigned short int 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 1.2E-38 to 3.4E+38 %f
double 8 1.7E-308 to 1.7E+308 %lf
long double 16 3.4E-4932 to 1.1E+4932 %Lf

Integer Types

The integer data type in C is used to store the whole numbers without decimal values. Octal values, hexadecimal values, and decimal values can be stored in int data type in C. We can determine the size of the int data type by using the sizeof operator in C. Unsigned int data type in C is used to store the data values from zero to positive numbers but it can’t store negative values like signed int. Unsigned int is larger in size than signed int and it uses “%u” as a format specifier in C programming language. Below is the programming implementation of the int data type in C.

  • Range: -2,147,483,648 to 2,147,483,647
  • Size: 2 bytes or 4 bytes
  • Format Specifier: %d

Note: The size of an integer data type is compiler-dependent, when processors are 16-bit systems, then it shows the output of int as 2 bytes. And when processors are 32-bit then it shows 2 bytes as well as 4 bytes.

Name already in use

docs / docs / csharp / language-reference / builtin-types / integral-numeric-types.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Integral numeric types (C# reference)

The integral numeric types represent integer numbers. All integral numeric types are value types. They’re also simple types and can be initialized with literals. All integral numeric types support arithmetic, bitwise logical, comparison, and equality operators.

Characteristics of the integral types

C# supports the following predefined integral types:

C# type/keyword Range Size .NET type
sbyte -128 to 127 Signed 8-bit integer xref:System.SByte?displayProperty=nameWithType
byte 0 to 255 Unsigned 8-bit integer xref:System.Byte?displayProperty=nameWithType
short -32,768 to 32,767 Signed 16-bit integer xref:System.Int16?displayProperty=nameWithType
ushort 0 to 65,535 Unsigned 16-bit integer xref:System.UInt16?displayProperty=nameWithType
int -2,147,483,648 to 2,147,483,647 Signed 32-bit integer xref:System.Int32?displayProperty=nameWithType
uint 0 to 4,294,967,295 Unsigned 32-bit integer xref:System.UInt32?displayProperty=nameWithType
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed 64-bit integer xref:System.Int64?displayProperty=nameWithType
ulong 0 to 18,446,744,073,709,551,615 Unsigned 64-bit integer xref:System.UInt64?displayProperty=nameWithType
nint Depends on platform (computed at runtime) Signed 32-bit or 64-bit integer xref:System.IntPtr?displayProperty=nameWithType
nuint Depends on platform (computed at runtime) Unsigned 32-bit or 64-bit integer xref:System.UIntPtr?displayProperty=nameWithType

In all of the table rows except the last two, each C# type keyword from the leftmost column is an alias for the corresponding .NET type. The keyword and .NET type name are interchangeable. For example, the following declarations declare variables of the same type:

The nint and nuint types in the last two rows of the table are native-sized integers. Starting in C# 9.0, you can use the nint and nuint keywords to define native-sized integers. These are 32-bit integers when running in a 32-bit process, or 64-bit integers when running in a 64-bit process. They can be used for interop scenarios, low-level libraries, and to optimize performance in scenarios where integer math is used extensively.

The native-sized integer types are represented internally as the .NET types xref:System.IntPtr?displayProperty=nameWithType and xref:System.UIntPtr?displayProperty=nameWithType. Starting in C# 11, the nint and nuint types are aliases for the underlying types.

The default value of each integral type is zero, 0 .

Each of the integral types has MinValue and MaxValue properties that provide the minimum and maximum value of that type. These properties are compile-time constants except for the case of the native-sized types ( nint and nuint ). The MinValue and MaxValue properties are calculated at runtime for native-sized types. The sizes of those types depend on the process settings.

Use the xref:System.Numerics.BigInteger?displayProperty=nameWithType structure to represent a signed integer with no upper or lower bounds.

Integer literals can be

  • decimal: without any prefix
  • hexadecimal: with the 0x or 0X prefix
  • binary: with the 0b or 0B prefix

The following code demonstrates an example of each:

The preceding example also shows the use of _ as a digit separator. You can use the digit separator with all kinds of numeric literals.

The type of an integer literal is determined by its suffix as follows:

If the literal has no suffix, its type is the first of the following types in which its value can be represented: int , uint , long , ulong .

[!NOTE] Literals are interpreted as positive values. For example, the literal 0xFF_FF_FF_FF represents the number 4294967295 of the uint type, though it has the same bit representation as the number -1 of the int type. If you need a value of a certain type, cast a literal to that type. Use the unchecked operator, if a literal value cannot be represented in the target type. For example, unchecked((int)0xFF_FF_FF_FF) produces -1 .

If the literal is suffixed by U or u , its type is the first of the following types in which its value can be represented: uint , ulong .

If the literal is suffixed by L or l , its type is the first of the following types in which its value can be represented: long , ulong .

[!NOTE] You can use the lowercase letter l as a suffix. However, this generates a compiler warning because the letter l can be confused with the digit 1 . Use L for clarity.

If the literal is suffixed by UL , Ul , uL , ul , LU , Lu , lU , or lu , its type is ulong .

If the value represented by an integer literal exceeds xref:System.UInt64.MaxValue?displayProperty=nameWithType, a compiler error CS1021 occurs.

If the determined type of an integer literal is int and the value represented by the literal is within the range of the destination type, the value can be implicitly converted to sbyte , byte , short , ushort , uint , ulong , nint or nuint :

As the preceding example shows, if the literal’s value isn’t within the range of the destination type, a compiler error CS0031 occurs.

You can also use a cast to convert the value represented by an integer literal to the type other than the determined type of the literal:

You can convert any integral numeric type to any other integral numeric type. If the destination type can store all values of the source type, the conversion is implicit. Otherwise, you need to use a cast expression to perform an explicit conversion. For more information, see Built-in numeric conversions.

Native sized integers

Native sized integer types have special behavior because the storage is determined by the natural integer size on the target machine.

To get the size of a native-sized integer at run time, you can use sizeof() . However, the code must be compiled in an unsafe context. For example:

. code language=»csharp» source=»snippets/shared/NativeIntegerTypes.cs» .

You can also get the equivalent value from the static xref:System.IntPtr.Size?displayProperty=nameWithType and xref:System.UIntPtr.Size?displayProperty=nameWithType properties.

To get the minimum and maximum values of native-sized integers at run time, use MinValue and MaxValue as static properties with the nint and nuint keywords, as in the following example:

. code language=»csharp» source=»snippets/shared/NativeIntegerTypes.cs» .

You can use constant values in the following ranges:

  • For nint : xref:System.Int32.MinValue?displayProperty=nameWithType to xref:System.Int32.MaxValue?displayProperty=nameWithType.
  • For nuint : xref:System.UInt32.MinValue?displayProperty=nameWithType to xref:System.UInt32.MaxValue?displayProperty=nameWithType.

The compiler provides implicit and explicit conversions to other numeric types. For more information, see Built-in numeric conversions.

There’s no direct syntax for native-sized integer literals. There’s no suffix to indicate that a literal is a native-sized integer, such as L to indicate a long . You can use implicit or explicit casts of other integer values instead. For example:

C# language specification

For more information, see the following sections of the C# language specification:

C Data Types

In this tutorial, you will learn about basic data types such as int, float, char etc. in C programming.

Video: Data Types in C Programming

In C programming, data types are declarations for variables. This determines the type and size of data associated with variables. For example,

Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.

Basic types

Here’s a table containing commonly used types in C programming for quick access.

Type Size (bytes) Format Specifier
int at least 2, usually 4 %d , %i
char 1 %c
float 4 %f
double 8 %lf
short int 2 usually %hd
unsigned int at least 2, usually 4 %u
long int at least 4, usually 8 %ld , %li
long long int at least 8 %lld , %lli
unsigned long int at least 4 %lu
unsigned long long int at least 8 %llu
signed char 1 %c
unsigned char 1 %c
long double at least 10, usually 12 or 16 %Lf

Integers are whole numbers that can have both zero, positive and negative values but no decimal values. For example, 0 , -5 , 10

We can use int for declaring an integer variable.

Here, id is a variable of type integer.

You can declare multiple variables at once in C programming. For example,

The size of int is usually 4 bytes (32 bits). And, it can take 2 32 distinct states from -2147483648 to 2147483647 .

float and double

float and double are used to hold real numbers.

In C, floating-point numbers can also be represented in exponential. For example,

What’s the difference between float and double ?

The size of float (single precision float data type) is 4 bytes. And the size of double (double precision float data type) is 8 bytes.

Keyword char is used for declaring character type variables. For example,

The size of the character variable is 1 byte.

void is an incomplete type. It means «nothing» or «no type». You can think of void as absent.

For example, if a function is not returning anything, its return type should be void .

Note that, you cannot create variables of void type.

short and long

If you need to use a large number, you can use a type specifier long . Here’s how:

Here variables a and b can store integer values. And, c can store a floating-point number.

If you are sure, only a small integer ( [−32,767, +32,767] range) will be used, you can use short .

You can always check the size of a variable using the sizeof() operator.

signed and unsigned

In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by using them:

  • signed — allows for storage of both positive and negative numbers
  • unsigned — allows for storage of only positive numbers

Here, the variables x and num can hold only zero and positive values because we have used the unsigned modifier.

Considering the size of int is 4 bytes, variable y can hold values from -2 31 to 2 31 -1 , whereas variable x can hold values from 0 to 2 32 -1 .

Derived Data Types

Data types that are derived from fundamental data types are derived types. For example: arrays, pointers, function types, structures, etc.

Int c что это

unsigned long long

Определение чисел в различных системах

Си позволяет определять числа в разных числовых системых. Числа в двоичной системе начинаются с символов 0b , после которых идет набор 1 и 0, которые представляют число. Восьмеричные числа начинаются с числа 0, за которым могут идти цифры от 0 до 7. Щестнадцатеричные числа начинаются с 0x или 0X , за которыми следуют шестнадцатеричные цифры от 0 до 9 и от A до F. Например:

В данном случае определены четыре переменных, но каждая из них хранит одно и то же число — 11, записанное в разных системах исчисления.

Числа с плавающей точкой

Числа с плавающей точкой представлены тремя типами: float , double , long double . В качестве разделителя между целой и дробной частями применяется точка. По умолчанию все дробные числа представляют тип double , который занимает 8 байт:

Для вывода значения double на консоль используется спецификаторы f и lf . Чтобы указать, что число представляет тип float , применяется суффикс f , а для long double — суффикс l :

Стоит отметить, что для вывода данных типа long double на консоль применяется спецификатор Lf , однако на некоторых платформах он может работать некорректно, например, показывать 0.

Символы

Переменным типа char можно присвоить один символ в одинарных кавычках:

Здесь определяется переменная letter, которая хранит символ ‘A’. Однако в реальности переменная типа char хранит число. И когда переменной присваивается символ, она получает числовой код этого символа из таблицы, которая сопоставляет числовые коды и символы. Наиболее распространена таблица ASCII. Она сопоставляет символы с числами от 0 до 127. Но есть и другие таблицы, которые, как правило, эту таблицу ASCII. Например, возьмем выше определенную переменную letter и выведем ее содержимое на консоль:

Числовой код символа ‘A’ в таблице ASCII равен 65. Для наглядности в программе два раза выводим значение переменной letter. Но в первом случае используем спецификатор %d для вывода числового кода символа, а во втором случае применяется спецификатор %c , который позволяет вывести на консоль сам символ. То есть при выполнении программа выведет на консоль:

Вместо символа в одинарных кавычках мы могли бы присвоить напрямую числовой код:

И мы получили бы тот же самый результат.

typedef

Оператор typedef позволяет для определенного типа псевдоним. Это может потребоваться, например, когда название некоторого типа довольно большое, и мы хотим его сократить.

Общая форма оператора

Например, зададим для типа unsigned char псевдоним BYTE :

И мы сможем использовать этот тип как и любой другой:

Размер типов данных

В выше приведенном списке для каждого типа указан размер, который он занимает в памяти. Однако стоит отметить, что предельные размеры для типов разработчики компиляторов могут выбирать самостоятельно, исходя из аппаратных возможностей компьютера. Стандарт устанавливает лишь минимальные значения, которые должны быть. Например, для типов int и short минимальное значение — 16 бит, для типа long — 32 бита. При этом размер типа long должен быть не меньше размера типа int, а размер типа int — не меньше размера типа short. Но в целом для типов используются те размеры, которые указаны выше при описании типов данных.

Однако бывают ситуации, когда необходимо точно знать размер определенного типа. И для этого в C есть оператор sizeof() , который возвращает размер памяти в байтах, которую занимает переменная:

При этом при определении переменных важно понимать, что значение переменной не должно выходить за те пределы, которые очерчены для ее типа. Например:

Компилятор GCC при компиляции программы с этой строкой выдаст ошибку о том, что значение -65535 не входит в диапазон допустимых значений для типа unsigned short int.

Читать:
Passmark performancetest как пользоваться

Похожие статьи