Integers int. char, short, int, and long types

This section will cover the main data types in C++, these data types are also called built-in data types. The C++ programming language is an extensible programming language. The concept of extensible means that in addition to built-in data types, you can create your own data types. Therefore, there are a huge number of data types in C++. We will study only the main ones.

Table 1 - C++ Data Types
Type byte Range of accepted values

integer (boolean) data type

bool 1 0 / 255

integer (character) data type

char 1 0 / 255

integer data types

short int 2 -32 768 / 32 767
unsigned short int 2 0 / 65 535
int 4
unsigned int 4 0 / 4 294 967 295
long int 4 -2 147 483 648 / 2 147 483 647
unsigned long int 4 0 / 4 294 967 295

floating point data types

float 4 -2 147 483 648.0 / 2 147 483 647.0
long float 8
double 8 -9 223 372 036 854 775 808 .0 / 9 223 372 036 854 775 807.0

Table 1 shows the main data types in C++. The entire table is divided into three columns. The first column contains a reserved word that will define each data type. The second column indicates the number of bytes that are allocated for a variable with the corresponding data type. The third column shows the range of valid values. Please note that in the table all data types are arranged from smallest to largest.

bool data type

The first one in the table is the bool data type integer data type, since the range of valid values ​​is integers from 0 to 255. But as you have already noticed, it is written in parentheses - boolean data type, and this is also true. As bool used solely to store the results of boolean expressions. A boolean expression can have one of two results true or false . true if the boolean expression is true, false if the boolean expression is false.

But since the range of allowed values ​​of the bool data type is from 0 to 255, it was necessary to somehow compare this range with the logical constants true and false defined in the programming language. Thus, the constant true is equivalent to all numbers from 1 to 255 inclusive, while the constant false is equivalent to only one integer - 0. Consider a program using the bool data type.

// data_type.cpp: defines the entry point for the console application. #include "stdafx.h" #include using namespace std; int main(int argc, char* argv) ( bool boolean = 25; // bool type variable named boolean if (boolean) // if statement condition cout<< "true = " << boolean << endl; // выполнится в случае истинности условия else cout << "false = " << boolean << endl; // выполнится в случае, если условие ложно system("pause"); return 0; }

AT line 9type variable declared bool , which is initialized to 25. Theoretically, afterline 9, in a boolean variable should contain the number 25, but in fact this variable contains the number 1. As I said, the number 0 is a false value, the number 1 is a true value. The bottom line is that in a variable of type bool can contain two values ​​- 0 (false) or 1 (true). Whereas under data type bool a whole byte is allocated, which means that a variable of type bool can contain numbers from 0 to 255. Only two values ​​0 and 1 are needed to determine false and true values. The question arises: “What are the other 253 values ​​for?”.

Based on this situation, we agreed to use the numbers from 2 to 255 as equivalent to the number 1, that is, true. That's exactly why the boolean variable contains the number 25 and not 1. In lines 10-13 is declared, which transfers control to the statement in line 11 if the condition is true, and the operator in line 13 if the condition is false. See the result of the program in Figure 1.

True = 1 Press any key to continue. . .

Figure 1 - bool data type

char data type

The char data type is an integer data type that is used to represent characters. That is, each character corresponds to a certain number from the range. The char data type is also called a character data type, since the graphical representation of characters in C++ is possible thanks to char . To represent characters in C ++, the char data type is assigned one byte, in one byte - 8 bits, then we raise two to the power of 8 and get the value 256 - the number of characters that can be encoded. Thus, using the char data type, any of the 256 characters can be displayed. All encoded characters are represented in .

ASCII (from the English American Standard Code for Information Interchange) is the American standard code for information interchange.

Consider a program using the char data type.

// symbols.cpp: defines the entry point for the console application. #include "stdafx.h" #include using namespace std; int main(int argc, char* argv) ( char symbol = "a"; // declaring a variable of type char and initializing it with symbol "a" cout<< "symbol = " << symbol << endl; // печать символа, содержащегося в переменной symbol char string = "сайт"; // объявление символьного массива (строки) cout << "string = " << string << endl; // печать строки system("pause"); return 0; }

So in line 9a variable named symbols , it is assigned the symbol value"a" ( ASCII code). AT line 10 cout operator prints the character contained in the variable symbol . AT line 11a string array named string , and the size of the array is set implicitly. A string is stored in a string array"website" . Note that when we saved the symbol into a variable like char , then after the equal sign we put single quotes, in which we wrote the character. When initializing a string array with some string, double quotes are placed after the equal sign, in which some string is written. Like a regular character, strings are output using the operator cout, line 12. The result of the program is shown in Figure 2.

Symbol = a string = website Press any key to continue. . .

Figure 2 - Data type char

Integer data types

Integer data types are used to represent numbers. There are already six of them in table 1: short int , unsigned short int , int , unsigned int , long int , unsigned long int . All of them have their own memory size and range of accepted values. Depending on the compiler, the amount of memory used and the range of accepted values ​​may vary. In Table 1, all ranges of accepted values ​​and sizes of occupied memory are taken for the MVS2010 compiler. Moreover, all data types in Table 1 are arranged in ascending order of the size of the occupied memory and the range of accepted values. The range of accepted values, one way or another, depends on the size of the occupied memory. Accordingly, the larger the size of the occupied memory, the larger the range of accepted values. Also, the range of accepted values ​​changes if the data type is declared with the prefix unsigned - without a sign. The prefix unsigned means that the data type cannot store signed values, and then the range of positive values ​​is doubled, for example, data types short int and unsigned short int .

Prefixes of integer data types:

short the prefix shortens the data type to which it is applied by reducing the size of the memory it occupies;

long prefix lengthens the data type to which it is applied by increasing the amount of memory it occupies;

unsigned (unsigned) - the prefix doubles the range of positive values, while the range of negative values ​​cannot be stored in this data type.

So, in fact, we have one integer type to represent integers - this is the int data type. The prefixes short , long , unsigned give rise to a variety of int data types that differ in the size of the memory occupied and (or) the range of accepted values.

Floating point data types

There are two floating point data types in C++: float and double . Floating point data types are designed to store floating point numbers. The float and double data types can store both positive and negative floating point numbers. The float data type has half the amount of memory occupied by the double data type, which means that the range of accepted values ​​is also smaller. If the float data type is declared with a long prefix, then the range of accepted values ​​will become equal to the range of accepted values ​​of the double data type. Basically, floating point data types are needed for solving problems with high computational precision, for example, money transactions.

So, we have considered the main points regarding the basic data types in C ++. It remains only to show where all these ranges of accepted values ​​\u200b\u200band the sizes of the occupied memory come from. And for this, we will develop a program that will calculate the main characteristics of all the data types discussed above.

// data_types.cpp: defines the entry point for the console application. #include "stdafx.h" #include // I/O manipulation library #include // header file of mathematical functions #include using namespace std; int main(int argc, char* argv) ( cout<< " data type " << "byte" << " " << " max value "<< endl // column headings <<"bool = " << sizeof(bool) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных bool*/ << (pow(2,sizeof(bool) * 8.0) - 1) << endl << "char = " << sizeof(char) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных char*/ << (pow(2,sizeof(char) * 8.0) - 1) << endl << "short int = " << sizeof(short int) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных short int*/ << (pow(2,sizeof(short int) * 8.0 - 1) - 1) << endl << "unsigned short int = " << sizeof(unsigned short int) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных unsigned short int*/ << (pow(2,sizeof(unsigned short int) * 8.0) - 1) << endl << "int = " << sizeof(int) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных int*/ << (pow(2,sizeof(int) * 8.0 - 1) - 1) << endl << "unsigned int = " << sizeof(unsigned int) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных unsigned int*/ << (pow(2,sizeof(unsigned int) * 8.0) - 1) << endl << "long int = " << sizeof(long int) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных long int*/ << (pow(2,sizeof(long int) * 8.0 - 1) - 1) << endl << "unsigned long int = " << sizeof(unsigned long int) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных undigned long int*/ << (pow(2,sizeof(unsigned long int) * 8.0) - 1) << endl << "float = " << sizeof(float) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных float*/ << (pow(2,sizeof(float) * 8.0 - 1) - 1) << endl << "double = " << sizeof(double) << " " << fixed << setprecision(2) /*вычисляем максимальное значение для типа данных double*/ << (pow(2,sizeof(double) * 8.0 - 1) - 1) << endl; system("pause"); return 0; }

This program is posted so that you can view the characteristics of data types in your system. You should not understand the code, since the program uses control statements that you, most likely, are not yet familiar with. For a superficial acquaintance with the program code, I will explain some points below. Operator sizeof() calculates the number of bytes allocated for a data type or variable. Function pow(x,y) elevates the value x to the power of y , this function is available from the header file . fixed and setprecision() manipulators available from header file . The first one is fixed , passes values ​​in a fixed form to the output stream. Manipulator setprecision(n) displays n decimal places. The maximum value of some data type is calculated using the following formula:

Max_val_type = 2^(b * 8 - 1) - 1; // for data types with negative and positive numbers // where, b is the number of bytes allocated in memory for a variable with this data type // multiply by 8, since there are 8 bits in one byte // subtract 1 in brackets, since the range numbers must be halved for positive and negative values ​​// subtract 1 at the end since the range of numbers starts from zero // unsigned data types max_val_type = 2^(b * 8) - 1; // for data types with only positive numbers // explanations for the formula are similar, only one is not subtracted from the parenthesis

An example of how the program works can be seen in Figure 3. The first column shows the main data types in C++, the second column shows the amount of memory allocated for each data type, and the third column shows the maximum value that the corresponding data type can contain. The minimum value is found similarly to the maximum. In data types prefixed with unsigned, the minimum value is 0.

Data type byte max value bool = 1 255.00 char = 1 255.00 short int = 2 32767.00 unsigned short int = 2 65535.00 int = 4 2147483647.00 unsigned int = 4 4294967295.00 long int = 4 2147483647.00 unsigned long int = 4 4294967295.00 float = 4 2147483647.00 double = 8 9223372036854775808.00 Press any key to continue. . .

Figure 3 - C++ Data Types

If, for example, a variable of type short int is assigned the value 33000, then the bit grid will overflow, since the maximum value in a variable of type short int is 32767. That is, some other value will be stored in a variable of type short int, most likely it will be negative. Since we've touched on the int data type, it's worth noting that you can omit the int keyword and write, for example, just short . The compiler will interpret such a notation as short int . The same applies to long and unsigned prefixes. For example:

// short for data type int short a1; // same as short int long a1; // same as long int unsigned a1; // same as unsigned int unsigned short a1; // same as unsigned short int

Tags: C variables. char, int, unsigned, long, long long, float, double, long double, long float, lexical scoping. Declaring variables. Area of ​​visibility. Variable initialization. Variable names. exponential form.

Variables

Variables are used to store values ​​(sic!). A variable is characterized by a type and a name. Let's start with the name. In C, a variable can start with an underscore or a letter, but not with a number. The variable can include English characters, numbers, and underscores. The variable must not match keywords (these are special words that are used as control structures, to define types, etc.)

auto double int struct
break else long switch
register typedef char external
return void case float
unsigned default for signed
union do if sizeof
volatile continue enum short
while inline
As well as a number of other words specific to this version of the compiler, for example far, near, tiny, huge, asm, asm_ etc.

For example, correct identifiers
a, _, _1_, Sarkasm, a_long_variable, aLongVariable, var19, defaultX, char_type
unfaithful
1a, $value, a-long-value, short

C is a case-sensitive language. Variables named a and A, or end and END, or perfectDark and PerfectDarK are different variables.

Variable types

The variable type determines

  • 1) The size of the variable in bytes (how many bytes of memory the computer will allocate to store the value)
  • 2) Representation of a variable in memory (how bits will be located in binary form in the allocated memory area).
There are several basic types in C. Let's divide them into two groups - integers and floating point numbers.

whole

  • char- size 1 byte. Always! This must be remembered.
  • short- size 2 bytes
  • int- size 4 bytes
  • long- size 4 bytes
  • long long- size 8 bytes.
A remark should be made here. The size of variables in C is not explicitly defined as the size in bytes. The standard only states that

char<= short <= int <= long <= long long

The above values ​​are specific to the VC2012 compiler on a 32-bit machine. So, if your program depends on the size of a variable, don't be too lazy to find out its size.

Now let's define the maximum and minimum number that a variable of each type can store. Numbers can be both positive and negative. Negative numbers use one bit to store the sign. Sometimes the sign is necessary (for example, we store a bank account, temperature, coordinate, etc.), and sometimes it is not necessary (weight, array size, person's age, etc.). To do this, C uses the type modifier signed and unsigned. unsigned char - all 8 bits under the number, in total we have a set of numbers from 00000000 to 11111111 in binary form, that is, from 0 to 255 signed char from -128 to 128. By default, variables are signed. Therefore, writing char and signed char are equivalent.

Tab. 1 Size of integer types in C.
Type Size, bytes Minimum value Maximum value
unsigned char 1 0 255
signed char
(char)
1 -128 127
unsigned short 2 0 65535
signed short
(short)
2 -32768 32767
unsigned int
(unsigned)
4 0 4294967296
signed int
(int)
4 -2147483648 2147483647
unsigned long 4 0 4294967296
signed long
(long)
4 -2147483648 2147483647
unsigned long long 8 0 18446744073709551615
signed long long
(long long)
8 -9223372036854775808 9223372036854775807

sizeof

There is an operator in C that allows you to get the size of a variable in bytes. sizeof is a variable, or sizeof(variable) or sizeof(type). It's an operator, because the function has no way to get information about the size of types at runtime. Let's write a small program to check the sizes of the variables.

#include #include int main() ( char c; short s; int i; long l; long long L; //Calling sizeof as a "function" printf("sizeof(char) = %d\n", sizeof(c)); printf ("sizeof(short) = %d\n", sizeof(s)); printf("sizeof(int) = %d\n", sizeof(i)); printf("sizeof(long) = %d\ n", sizeof(l)); printf("sizeof(long long) = %d\n", sizeof(L)); //Call as operator printf("sizeof(char) = %d\n", sizeof c); printf("sizeof(short) = %d\n", sizeof s); printf("sizeof(int) = %d\n", sizeof i); printf("sizeof(long) = %d\ n", sizeof l); printf("sizeof(long long) = %d\n", sizeof L); _getch(); )

(I think it's clear that variables can have any valid name). This program could have been written in a simpler way.

#include #include int main() ( printf("sizeof(char) = %d\n", sizeof(char)); printf("sizeof(short) = %d\n", sizeof(short)); printf("sizeof( int) = %d\n", sizeof(int)); printf("sizeof(long) = %d\n", sizeof(long)); printf("sizeof(long long) = %d\n", sizeof(long long)); //cannot call sizeof as operator on type name //sizeof int - compile error _getch(); )

In C, the same type can have more than one name.
short === short int
long === long int
long long === long long int
unsigned int === unsigned

floating point types

  • float- 4 bytes,
  • long float- 8 bytes
  • double- 8 bytes
  • long double- 8 bytes.
Here are also the values ​​for VC2012, according to the standard, the size of float types<= long float <= double <= long double все числа с плавающей точкой - со знаком.

Variable overflow

C doesn't care about variable overflow. This means that by constantly increasing the value of, say, an int variable, we will eventually "reset the value"

#include #include void main() ( unsigned a = 4294967295; int b = 2147483647; //Unsigned type overflow printf("%u\n", a); a += 1; printf("%u", a); //Overflow signed type printf("%d\n", b); b += 1; printf("%d", b); getch(); )

In general, variable overflow behavior is only defined for the type unsigned: An unsigned integer will reset the value. For other types, anything can happen, and if you need to watch for overflow, do it manually by checking arguments, or use other methods depending on the compiler and processor architecture.

Postfix type designation

When working with numbers, you can use the characters at the end of the number to explicitly indicate its type, for example

  • 11 - number of type int
  • 10u - unsigned
  • 22l or 22L - long
  • 3890ll or 3890LL - long long (also lL or Ll)
  • 80.0f or 80.f or 80.0F - float (necessary to have a decimal point in the record)
  • 3.0 - double number
Exponential notation also denotes a number of double type by default. #include #include int main() ( printf("sizeof(int) = %d\n", sizeof(10)); printf("sizeof(unigned) = %d\n", sizeof(10u)); printf("sizeof( long) = %d\n", sizeof(10l)); printf("sizeof(long long) = %d\n", sizeof(10ll)); printf("sizeof(float) = %d\n", sizeof(10.f)); printf("sizeof(double) = %d\n", sizeof(10.)); printf("sizeof(double) = %d\n", sizeof(10e2)); getch (); )

The following code, however, will not produce errors because there is an implicit type conversion

Int a = 10u; double g = 3.f;

Hexadecimal and octal format

When working with numbers, you can use hexadecimal and octal representations. Numbers in hexadecimal start with 0x, in octal start with zero. Accordingly, if the number starts from zero, then it should not contain digits higher than 7:

#include #include void main() ( int x = 0xFF; int y = 077; printf("hex x = %x\n", x); printf("dec x = %d\n", x); printf("oct x = %o\n", x); printf("oct y = %o\n", y); printf("dec y = %d\n", y); printf("hex y = %x", y); getch(); )

Exponential representation of numbers

The exponential form of representing a number is the representation of a number in the form M e ± p , where M- mantis of the number, p- power of ten. In this case, the mantissa must have one non-zero sign before the decimal point.
For example 1.25 === 1.25e0, 123.5 === 1.235e2, 0.0002341 === 2.341e-4 etc.
Views 3.2435e7 is equivalent to 3.2435e+7
There is another representation ("engineering"), in which the degree must be a multiple of three. For example 1.25 === 1.25e0, 123.5 === 123.5e0, 0.0002341 === 234.1e-6, 0.25873256 === 258.73256e-3 etc.

Declaring Variables

In C, variables are always declared at the beginning of a block (a block is a piece of code delimited by curly braces)

<возвращаемый тип> <имя функции> (<тип> <аргумент>[, <тип> <аргумент>]) ( variable declaration everything else )

When declaring a variable, its type and name are written.

int a; double parameter;

You can declare multiple variables of the same type by separating the names with a comma

Long long arg1, arg2, arg3;

for example

#include #include int main() ( int a = 10; int b; while (a>0)( int z = a*a; b += z; ) )

Variables are declared here a and b inside a function main, and variable z inside the loop body. The following code will cause a compilation error

int main() ( int i; i = 10; int j; )

This is because the variable declaration comes after the assignment statement. When declaring variables, you can immediately initialize them.
int i = 0;
At the same time, initialization when declaring a variable is not considered a separate statement, so the following code will work

int main() ( int i = 10; int j; )

The initial value of the variable

It is very important to remember that variables in C are not initialized to zero by default, as in many other programming languages. After the variable is declared, it stores "garbage" - a random value that remains in the memory area that was allocated for the variable. This is primarily due to the optimization of the program: if there is no need for initialization, then there is no need to spend resources to write zeros (note: global variables are initialized with zeros, why so, read this article).

#include #include int main() ( int i; printf("%d", i); getch(); )

If you run this program on VC, then a warning will fly out during execution
Run-Time Check Failure #3 - The variable "i" is being used without being initialized.
If you click "Continue", the program will display "garbage". In many other compilers, there will be no warning when the program is executed.

Variable scope

Variables can be local (declared inside some function) and global. The global variable is visible to all functions declared in this file. A local variable is limited by its scope. When I say that a variable is "visible in some place", it means that in this place it is defined and can be used. For example, consider a program that has a global variable

#include #include int global = 100; void foo() ( printf("foo: %d\n", global); ) void bar(int global) ( printf("bar: %d\n", global); ) int main() ( foo() ; bar(333); getch(); )

Will be displayed
foo:100
bar: 333
Here is a global variable global visible to all functions. But the function argument overwrites the global variable, so passing the argument 333 prints the local value 333.
Here is another example

#include #include int global = 100; int main() ( int global = 555; printf("%d\n", global); getch(); )

The program will print 555. Just like in the previous case, the local variable is "more important". A variable declared in some scope is not visible outside of it, for example

#include #include int global = 100; int main() ( int x = 10; ( int y = 30; printf("%d", x); ) printf("%d", y); )

This example will not compile because the variable y exists only within its block.
Here is another example where variables declared inside a block overlap each other

#include #include int global = 100; int main() ( int x = 10; ( int x = 20; ( int x = 30; printf("%d\n", x); ) printf("%d\n", x); ) printf( "%d\n", x); getch(); )

The program will output
30
20
10
Global variables should be avoided. You can hear this very often. Let's try to figure out why. In your simple projects, global variables look quite normal. But imagine that you have an application that

  • 1) Developed by several people and consists of hundreds of thousands of lines of code
  • 2) Works in multiple threads

First, a global variable, if it is visible to everyone, can be changed by any part of the program. You changed a global variable, you want to write it, and another part of the program has already overwritten a different value into it (in fact, this is a whole class of problems that arise in a multithreaded environment). Secondly, with large project sizes, it is impossible to keep track of who and when created global variables. The examples above show how variables can overlap, and the same will happen in a large project.

Of course, there are situations where global variables simplify the program, but such situations do not happen often and not in your homework, so DO NOT CREATE GLOBAL VARIABLES!
Variables can be not only integer and floating point. There are many other types that we will study further.

In the C language, the concepts of “data type” and “type modifier” are distinguished. The data type is integer and the modifier is signed or unsigned. A signed integer will have both positive and negative values, while an unsigned integer will only have positive values. There are five basic types in C language.

  • char - character.
  • A char type variable has a size of 1 byte, its values ​​are various characters from the code table, for example: 'f', ':', 'j' (when written in the program, they are enclosed in single quotes).

  • int is an integer.
  • The size of a variable of type int is not defined in the C standard. In most programming systems, the size of a variable of type int corresponds to the size of a whole machine word. For example, in compilers for 16-bit processors, an int variable has a size of 2 bytes. In this case, the signed values ​​of this variable can range from -32768 to 32767.

  • float is real.
  • The float keyword allows you to define floating point variables. Their values ​​have a fractional part separated by a dot, for example: -5.6, 31.28, etc. Real numbers can also be written in floating point form, for example: -1.09e+4. The number before the symbol "e" is called the mantissa, and after the "e" - the order. A float variable occupies 32 bits in memory. It can take values ​​in the range from 3.4e-38 to 3.4e+38.

  • double – real double precision;
  • The double keyword allows you to define a double-precision real variable. It takes up twice as much memory space as a float variable. A variable of type double can take values ​​in the range from 1.7e-308 to 1.7e+308.

  • void - has no value.
  • The void keyword is used to neutralize the value of an object, such as declaring a function that does not return any value.

Variable types:

Programs operate on a variety of data, which can be simple and structured. Simple data is integers and real numbers, symbols and pointers (addresses of objects in memory). Integers do not have, and real numbers have a fractional part. Structured data is arrays and structures; they will be discussed below.

A variable is a location in computer memory that has a name and stores some value. The value of a variable can change during program execution. When a new value is written to a cell, the old value is erased.

It is good style to name variables meaningfully. The variable name can contain from one to 32 characters. You can use lowercase and uppercase letters, numbers, and the underscore character, which is considered a letter in C. The first character must be a letter. The variable name cannot be the same as reserved words.

type char

char is the most economical type. The char type can be signed or unsigned. Denoted as "signed char" (signed type) and "unsigned char" (unsigned type). A signed type can store values ​​in the range -128 to +127. Unsigned - from 0 to 255. 1 byte of memory (8 bits) is allocated for a char type variable.

The signed and unsigned keywords indicate how the zero bit of the declared variable is interpreted, i.e. if the unsigned keyword is specified, then the zero bit is interpreted as part of the number, otherwise the zero bit is interpreted as a sign.

type int

The integer value int can be short (short) or long (long). The short keyword is placed after the signed or unsigned keywords. Thus, there are types: signed short int, unsigned short int, signed long int, unsigned long int.

A variable of type signed short int (signed short integer) can take values ​​from -32768 to +32767, unsigned short int (unsigned short integer) - from 0 to 65535. Exactly two bytes of memory (16 bits) are allocated for each of them.

When declaring a variable of type signed short int, the keywords signed and short can be omitted, and such a variable type can be declared simply int. It is also possible to declare this type with a single short keyword.

An unsigned short int variable can be declared as unsigned int or unsigned short.

Each signed long int or unsigned long int has 4 bytes of memory (32 bits). The values ​​of variables of this type can range from -2147483648 to 2147483647 and from 0 to 4294967295, respectively.

There are also variables of type long long int, for which 8 bytes of memory (64 bits) are allocated. They can be signed or unsigned. For a signed type, the range of values ​​is from -9223372036854775808 to 9223372036854775807, for an unsigned type, from 0 to 18446744073709551615. A signed type can also be declared simply with two long long keywords.

Type Range Hexadecimal range The size
unsigned char 0 … 255 0x00 ... 0xFF 8bit
signed char
or simply
char
-128 … 127 -0x80...0x7F 8bit
unsigned short int
or simply
unsigned int or unsigned short
0 … 65535 0x0000 ... 0xFFFF 16bit
signed short int or signed int
or simply
short or int
-32768 … 32767 0x8000…0x7FFF 16bit
unsigned long int
or simply
unsigned long
0 … 4294967295 0x00000000 ... 0xFFFFFFFF 32bit
signed long
or simply
long
-2147483648 … 2147483647 0x80000000 ... 0x7FFFFFFF 32bit
unsigned long long 0 … 18446744073709551615 0x0000000000000000 … 0xFFFFFFFFFFFFFFFF 64bit
signed long long
or simply
long long
-9223372036854775808 … 9223372036854775807 0x8000000000000000 ... 0x7FFFFFFFFFFFFF 64bit

Declaring Variables

Variables are declared in a declaration statement. A declaration statement consists of a type specification and a comma-separated list of variable names. There must be a semicolon at the end.

[modifiers] typespecifier id [, id] ...

Modifiers are keywords signed, unsigned, short, long.
A type specifier is a char or int keyword that specifies the type of the variable being declared.
The identifier is the name of the variable.

Charx; int a, b, c; unsigned long long y;

When declaring a variable, you can initialize it, that is, assign it an initial value.

int x = 100;

The number 100 will immediately be written to the variable x upon declaration. It is better to declare initialized variables in separate lines.

Data types

Data types are of particular importance in C# because it is a strongly typed language. This means that all operations are strictly type-checked by the compiler, and invalid operations are not compiled. Therefore, strong typing helps to eliminate bugs and improve the reliability of programs. To ensure type checking, all variables, expressions, and values ​​must be of a particular type. There is no such thing as a "typeless" variable in this programming language. Moreover, the value type determines the operations that are allowed to be performed on it. An operation that is allowed for one data type may not be allowed for another.

There are two general categories of built-in data types in C#: value types and reference types. They differ in the contents of the variable. Conceptually, the difference between the two is that a value type stores data directly, while a reference type stores a reference to a value.

These types are stored in different locations in memory: value types are stored in an area known as the stack, while reference types are stored in an area called the managed heap.

Let's take a look value types.

Integer types

C# defines nine integer types: char, byte, sbyte, short, ushort, int, uint, long, and ulong. But the char type is mainly used to represent characters and is therefore treated separately. The remaining eight integer types are for numeric calculations. Below are their range of representation of numbers and bit depth:

C# Integer Types
Type CTS type Bit depth Range
byte System.Byte 8 0:255
sbyte System.SByte 8 -128:127
short System.Int16 16 -32768: 32767
ushort System.UInt16 16 0: 65535
int System.Int32 32 -2147483648: 2147483647
uint System.UInt32 32 0: 4294967295
long System.Int64 64 -9223372036854775808: 9223372036854775807
ulong System.UInt64 64 0: 18446744073709551615

As the table above shows, C# defines both signed and unsigned versions of the various integer types. Signed integer types differ from their unsigned counterparts in the way they interpret the most significant bit of an integer. For example, if a program specifies a signed integer value, the C# compiler will generate code that uses the high-order bit of the integer as the sign flag. A number is considered positive if the sign flag is 0, and negative if it is 1.

Negative numbers are almost always represented by the two's complement method, in which all the binary digits of a negative number are first inverted, and then 1 is added to this number.

Probably the most common integer type in programming is type int. Variables of type int are often used for loop control, array indexing, and general-purpose math. When you need an integer value with a larger number representation range than the int type, then there are a number of other integer types for this purpose.

So, if the value needs to be stored without a sign, then for it you can choose uint type, for large signed values ​​- long type, and for large unsigned values, the type ulong. As an example, below is a program that calculates the distance from the Earth to the Sun in centimeters. To store such a large value, it uses a variable of type long:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class Program ( static void Main(string args) ( long result; const long km = 149800000; // distance in km. result = km * 1000 * 100; Console.WriteLine(result); Console.ReadLine(); ) ) )

All integer variables can be assigned values ​​in decimal or hexadecimal notation. In the latter case, the 0x prefix is ​​required:

Long x = 0x12ab;

If there is any uncertainty as to whether an integer value is of type int, uint, long, or ulong, then default accepted int. To explicitly specify which other integer type the value should have, the following characters can be added to the number:

Uint ui = 1234U; long l = 1234L; ulong ul = 1234UL;

U and L can also be written in lowercase, although the lowercase L can be visually confused with the number 1 (one).

floating point types

Floating point types allow you to represent numbers with a fractional part. There are two kinds of floating point data types in C#: float and double. They represent single and double precision numeric values, respectively. Thus, the float type is 32 bits, which approximately corresponds to the range of representation of numbers from 5E-45 to 3.4E+38. And the bit depth of the double type is 64 bits, which approximately corresponds to the range of representation of numbers from 5E-324 to 1.7E + 308.

The float data type is for smaller floating point values ​​that require less precision. The double data type is larger than float and offers a higher degree of precision (15 bits).

If a non-integer value is hard-coded in source code (for example, 12.3), then the compiler usually assumes that a value of type double is meant. If a value needs to be specified as a float, you will need to add an F (or f) character to it:

Float f = 12.3F;

Decimal data type

A decimal type is also provided to represent high precision floating point numbers. decimal, which is intended for use in financial calculations. This type is 128 bits wide to represent numeric values ​​ranging from 1E-28 to 7.9E+28. You probably know that normal floating-point arithmetic is prone to decimal rounding errors. These errors are eliminated by using the decimal type, which allows numbers to be represented with a precision of up to 28 (and sometimes 29) decimal places. Because it can represent decimal values ​​without rounding errors, this data type is especially useful for financial calculations:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class Program ( static void Main(string args) ( // *** Calculating the cost of an investment with *** // *** fixed rate of return*** decimal money, percent; int i; const byte years = 15 ; money = 1000.0m; percent = 0.045m; for (i = 1; i

The output of this program will be:

Symbols

In C#, characters are not represented by an 8-bit code, as in many other programming languages, such as C++, but by a 16-bit code called Unicode (Unicode). Unicode has such a wide character set that it covers characters from almost every natural language in the world. While many natural languages, including English, French, and German, are characterized by relatively small alphabets, a number of other languages, such as Chinese, use fairly large character sets that cannot be represented by an 8-bit code. To overcome this limitation, C# defines type char A that represents unsigned 16-bit values ​​between 0 and 65,535. However, the standard 8-bit ASCII character set is a subset of Unicode between 0 and 127. Therefore, ASCII characters are still valid in C# .

When writing a program in any language, you need to use different variables to store different information. Variables are nothing but reserved memory locations for storing values. This means that when you create a variable, you save some space in memory.

You can store information of various data types such as character, wide character, integer, floating point, double floating point, boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory .

Primitive built-in types

C++ offers the programmer a rich set of built-in as well as user-defined data types. The following tables list the seven main C++ data types:

type keyword
Boolean bool
character char
Integer int
floating point float
double floating point double
valueless void
wide character wchar_t

Some of the basic types can be modified using one or more of that type's modifiers:

  • signed
  • unsigned
  • short

The following table shows the type of the variable, the amount of memory it takes to store the value in memory, and what are the maximum and minimum values ​​that can be stored in such variables.

type Typical Bit Width typical range
char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65.535
signed short int Range -32768 to 32767
long int 4bytes -2,147,483,648 to 2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character

The size of the variables may differ from the size shown in the table above, depending on the compiler and computer you are using. Below is an example that will give the correct size for various data types on your computer.

#include using namespace std; int main() ( cout<< "Size of char: " << sizeof(char) << endl; cout << "Size of int: " << sizeof(int) << endl; cout << "Size of short int: " << sizeof(short int) << endl; cout << "Size of long int: " << sizeof(long int) << endl; cout << "Size of float: " << sizeof(float) << endl; cout << "Size of double: " << sizeof(double) << endl; cout << "Size of wchar_t: " << sizeof(wchar_t) << endl; return 0; }

This example uses endl, which introduces a newline character after each line, and the operator<< используется для передачи нескольких значений на экран. Мы также используем оператор sizeof() to get the size of various data types.

When the above code is compiled and executed, it produces the following output, which may vary from machine to machine:

Size of char: 1 Size of int: 4 Size of short int: 2 Size of long int: 4 Size of float: 4 Size of double: 8 Size of wchar_t: 4

typedef declarations

You can create a new name for an existing type with a typedef . Following is the simple syntax to define a new type using typedef:

Typedef type newname;

For example, the following tells the compiler that feet is another name for int:

Typedef int feet;

Now the following declaration is perfectly legal and creates an integer variable called distance:

Feet distance;

Listed types

An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values ​​of the type. Each enumerator is a constant whose type is an enum. The use of the keyword is required to create an enum. enum. General view of enum type:

Enum enum-name ( list of names ) var-list;

Here enum-name is the enum type name. The list of names is separated by a comma. For example, the following code defines an enumeration of colors called colors and a variable c of type color. Finally, c is assigned the value "blue".

Enum color ( red, green, blue ) c; c = blue;

By default, the value of the first name is 0, the second name has a value of 1, and the third name has a value of 2, and so on. But you can specify a name, a specific value, by adding an initializer. For example, in the following enumeration, green would have the value 5.

Enum color ( red, green = 5, blue );

Here blue will have the value 6 because each name will be greater than the previous one.

Loading...Loading...