The integer data type c of the function. Variables. Postfix type designation


TO data refers to any information presented in a form that allows you to automate its collection, storage and processing in a computer (numbers, symbols, bits, etc.).
The data in the program can be initial(specified at the program input) or processing results(intermediate or weekend).
All data - variables and constants - belongs to a certain type.
Each data type has its own associated value range(number of bytes for one value) and allowed operations.

Data types in C/C++ are divided into main And derivatives.
The main types include:

  1. void(empty type),
  2. int(integer type),
  3. float(real floating point numbers),
  4. double(double-precision floating-point real numbers),
  5. char(character type),
  6. bool- logical.

Composite types

To form other types of data, use main types + so-called specifiers. Data types created from standard types using specifiers are called composite data types. C++ defines four data type specifiers:
  1. short - short;
  2. long - long;
  3. signed-signed;
  4. unsigned
Derived types are:
  • arrays,
  • functions,
  • classes,
  • pointers,
  • links,
  • structures,
  • associations.

Character type

Type data char in computer memory always occupy 1 byte. This is due to the fact that usually a character type value is given as much memory as is necessary to store any of the 256 keyboard characters.
The character type can be signed or unsigned.
In signed quantities signed char you can store values ​​in the range from -128 to 127. Accordingly, the values ​​of variables of type unsigned char can range from 0 to 255.
Data type Value range Size
char -128...+127 1 byte
unsigned char 0...255 1 byte
signed char -128...127 1 byte

When working with character data, remember that if an expression contains single symbol, it must be enclosed in single quotes. A sequence of characters, i.e. a string, when used in expressions is in double quotes. For example: ‘F’ , ‘3’ , “Ivan”, “235”

integer type

Type data int in computer memory can occupy either 2, 4 or 8 bytes. It depends on the bitness of the processor.
By default, all integer types are considered signed, that is, the specifier signed(signed) can be omitted.
specifier unsigned(unsigned) allows only positive numbers to be represented.

Value Ranges of Integer Types

Data type Value range Size(byte)
int
signed int
signed long int
-2147483648 ... 2147483647 4
unsigned int
unsigned long int
0 ... 4294967295 4
short int
signed short int
-32768 ... 32767 2
unsigned short int 0... 65535 2
long long int \(-(2^{63}-1)...(2^{63}-1)\) 8
unsigned long
long int
\(0...(2^{64}-1)\) 8

Real type

The internal representation of a real number in computer memory is different from the representation of an integer. A floating point number is represented in exponential form. $$\pm mE\pm p$$ where m- mantissa (whole or fractional number with a decimal point), R- order (integer). In order to convert a number in exponential form to the usual fixed-point representation, it is necessary to multiply the mantissa by ten to the power of the order. For example: \(-6.42E+2=-6.42*10^(2)\)

Value ranges of real types

Data type Value range Size (byte)
float 3.4E-38 ... 3.4E+38 4
double 1.7E-308... 1.7E+308 8
long double 3.4E-4932 ... 3.4E+4932 10

The length of the mantissa determines the precision of the number, while the length of the exponent determines its range.
Float type data occupy 4 bytes, of which 1 bit is allocated for the sign, 8 bits for the exponent, and 23 bits for the mantissa. Since the highest digit of the mantissa is always 1, it is not stored.
Double type data occupy 8 bytes, they have -11 bits for the order and -52 bits for the mantissa, respectively.
The long type specifier before the double type name indicates that 10 bytes are allocated for the value.

boolean type

type variable bool can only take two values true(true) or false(lie). Any non-zero value is interpreted as true and, when converted to an integer type, takes on the value 1. False is represented in memory as 0.

Type void (empty)

The set of values ​​of this type is empty.
The void type is used for:
  • definitions of functions that do not return a value;
  • to specify an empty list of function arguments;
  • as the base type for pointers;
  • in a cast operation.

Declaring Variables

Variable is a named piece of memory that stores a value of a certain type.
The variable has Name(identifier) ​​and meaning.
Name is used to access the area of ​​memory where the value is stored.
Name(identifier) ​​is a combination of letters, numbers, and underscores that specifies the name of a variable, the name of a function, or a keyword in a program. The C/C++ language is case sensitive (i.e. Sum and sum will be treated as two different variables).
Where, type– a keyword that defines the amount of memory (number of bytes) allocated to store the value of a variable (as a program object), (int – integer, float, double – real, char – character, bool – logical);
Name– a unique variable identifier that specifies the symbolic address of the program object in the computer memory;
initiator– the initial value of the variable, which may not be in the description.
For example: Variables of the same type can be grouped by separating ",". The description of variables of different types is separated by “; ".
According to the place of declaration, variables in the C/C++ language can be divided into three classes:
  1. local - are declared inside the function and are available only in it;
  2. global - are described before all functions and are available from anywhere in the program;
  3. formal parameters of functions are described in the list of function parameters.
Example:

Integer type (int)

Type size int is not defined by the standard, but depends on the computer and compiler.

For a 16-bit processor, 2 bytes are allocated for values ​​of this type,

for 32-bit - 4 bytes.

specifier short in front of the type name indicates to the compiler that 2 bytes are required for the number, regardless of the processor bitness.

specifier long means that the integer value will take 4 bytes.

Thus, on a 16-bit computer, the equivalents of int and short int,

and on 32-bit, int and long int.

Internal representation values ​​of integer type - an integer in binary code. When using the specifier signed the most significant bit of the number is interpreted as sign (0 - positive number, 1 - negative). specifier unsigned allows only positive numbers to be represented, since the most significant digit is considered part of the number code. Thus, the range of values ​​of type int depends on the specifiers. Value ranges of integer type values ​​with different specifiers for IBM PC-compatible computers are given in the table "Value ranges of simple data types".

By default, all integer types are considered signed, which means that the signed specifier can be omitted.

The constants encountered in the program are assigned one or another type in accordance with their type. If for some reason it does not suit the programmer, you can explicitly specify the required type using the suffixes L, l (long) and U, u (unsigned). For example, the constant 32L will be of type long and occupy 4 bytes. You can use the L and U suffixes at the same time, for example, 0x22UL or 05Lu.

Note. The types short int, long int, signed int, and unsigned int can be shortened to short, long, signed, and unsigned, respectively.

Character type (char)

The value of a character type is the number of bytes sufficient to accommodate any character from the character set for a given computer, which led to the name of the type. Typically, this is 1 byte. The char type, like other integer types, can be signed or unsigned. Signed values ​​can store values ​​ranging from -128 to 127. When using the unsigned specifier, values ​​can range from 0 to 255. This is enough to store any character in the 256-character ASCII character set. char values ​​are also used to store integers.



Extended character type (wchar_t)

Type wchar_t designed to work with a set of characters for encoding which is not enough 1 byte. For example Unicode. The size of this type is implementation dependent; it usually matches the type short. String constants of type wchar_t are written with an L prefix, for example, L“Gates”.

Boolean type (bool)

Boolean values ​​can only take values true And false, which are reserved words. The internal representation of false is 0 (zero). Any other value is interpreted as true. When converting to an integer type true has a value of 1.

Floating point types (float, double and long double)

The C++ standard defines three data types for storing real values: float, double, and long double.

Floating point data types are stored differently in memory than integer data types. The internal representation of a real number consists of two parts - mantissa And order.

On IBM PC-compatible computers, values ​​like float occupy 4 bytes, of which one bit is allocated under the sign of the mantissa, 8 digits under order and 23 under the mantissa. The mantissa is a number greater than 1.0 but less than 2.0. Since the highest digit of the mantissa is always 1, it is not stored.

For values ​​of type double, occupying 8 bytes, 11 and 52 bits are allocated for the order and mantissa, respectively. The length of the mantissa determines the precision of the number, while the length of the exponent determines its range. As you can see from the table at the end of the entry, with the same number of bytes allocated for float and long int values, the ranges of their valid values ​​differ greatly because of the internal representation form.

specifier long before the type name double indicates that 10 bytes are allocated for its value.

Floating point constants are of type double by default. You can explicitly specify the type of a constant using the suffixes F, f (float) and L, l (long).

For example, the constant 2E+6L would be of type long double, and the constant 1.82f would be of type float.

When writing programs that are universal for different platforms, you cannot make assumptions about the size of the type int. To get it, you need to use the sizeof operator, which returns the size of the type in bytes.

For example, on an MS-DOS operating system, sizeof(int) will result in 2, and on Windows 98 or OS/2, the result will be 4.

The ANSI standard does not specify ranges of values ​​for the main types, only the ratios between their sizes are defined, for example:

sizeof(float) ≤ slzeof(double) ≤ sizeof(long double)
sizeof(char) ≤ slzeof(short) ≤ sizeof(int) ≤ sizeof(long)

Note. The minimum and maximum allowable values ​​for integer types are implementation dependent and are given in the header file (), characteristics of real types - in the file (), as well as in the class template numeric_limits

void type

In addition to those listed, the void type is one of the main types of the language, but the set of values ​​of this type is empty. It is used to define functions that do not return a value, to specify an empty list of function arguments, as the base type for pointers, and in cast operations.

Various types of integer and real types, differing in the range and precision of data representation, are introduced in order to enable the programmer to make the most efficient use of the capabilities of a particular hardware, since the speed of calculations and the amount of memory depend on the choice of type. But a program optimized for one type of computer may become non-portable to other platforms, so in general, dependencies on specific characteristics of data types should be avoided.

Type Value range Size (byte)
bool true and false
signed char -128 … 127
unsigned char 0 … 255
signed short int -32 768 … 32 767
unsigned short int 0 … 65 535
signed long int -2 147 483 648 … 2 147 483 647
unsigned long int 0 … 4 294 967 295
float 3.4e-38 … 3.4e+38
double 1.7e-308 … 1.7C+308
long double 3.4e-4932 … 3.4e+4932

Program structure

A C++ program consists of functions, descriptions And preprocessor directives. One of the functions must be named main. Program execution begins with the first statement of this function. The simplest function definition has the following format:

As a rule, a function is used to calculate some value, so its type is indicated before the function name. Below are the most important information about the functions:

  • if the function should not return a value, the void type is specified:
  • the body of the function is a block and is therefore enclosed in curly braces;
  • functions cannot be nested;
  • each statement ends with a semicolon (except for a compound statement).

An example of a program structure containing the functions main, fl and f2:

The program may consist of several modules(source files).

Notes on I/O in C++

The C++ language has no built-in I/O facilities - it is done using functions, types, and objects contained in the standard libraries.

Two methods are used: functions inherited from the C language, and C++ objects.

Basic C-style I/O functions:

int scanf (const char* format, ...) // input
int printf(const char* format, ...) // output

They perform formatted input and output of an arbitrary number of values ​​according to the format string. The format string contains characters that are copied to the stream (on the screen) or requested from the stream (from the keyboard) on input, and conversion specifications, beginning with a % sign, that are replaced by specific values ​​on input and output.

An example program using C-style I/O functions:

#include
int main() (
int i;
printf("Enter an integer\n");
scanf("%d", &i);
printf("You entered the number %d, thanks!", i);
return 0;
}

The first line of this program is a preprocessor directive, according to which a header file is inserted into the program text, containing a description of the input / output functions used in the program (in this case, angle brackets are an element of the language). All preprocessor directives begin with a # sign.

The third line is a description of an integer type variable named i.

The printf function on the fourth line prints the prompt "Enter an integer" and jumps to a new line according to the \n escape sequence. The scanf function stores the integer entered from the keyboard into the variable i (the & sign means the operation of getting the address), and the following statement displays the string specified in it, replacing the conversion specification with the value of this number.

Program using C++ class library:

#include
int main() (
int i;
cout<< "Введите целое число\n"; cin >> i;
cout<< "Вы ввели число " << i << ", спасибо!";
return 0;
}

The header file contains a description of a set of classes for managing input/output. It defines standard stream objects cin for keyboard input and cout for displaying on the screen, as well as streaming operations< < и чтения из потока >>.

You can use both methods of organizing input / output, but it is not recommended to mix them in one program.

A data type in programming is a collection of two sets: a set of values ​​and a set of operations that can be applied to them. For example, the non-negative integer data type, which consists of a finite set of natural numbers, can be applied to the operations of addition (+), multiplication (*), integer division (/), remainder (%), and subtraction (−).

A programming language typically has a set of primitive data types - types provided by the programming language as a basic built-in unit. In C++, the creator of the language calls such types fundamental types. The fundamental types in C++ are:

  • boolean (bool);
  • character (eg, char);
  • integer (e.g. int);
  • floating point (eg float);
  • enums (defined by the programmer);
  • void .

On top of the above, the following types are built:

  • pointers (eg, int*);
  • arrays (eg. char);
  • reference (e.g. double&);
  • other structures.

Let's move on to the concept of a literal (eg, 1, 2.4F, 25e-4, ‘a’, etc.): a literal is an entry in the source code of a program that represents a fixed value. In other words, a literal is simply a representation of an object (value) of some type in the program code. C++ has the ability to write integer values, floating point values, character, boolean, string values.

An integer type literal can be written as:

  • 10th number system. For example, 1205 ;
  • 8th number system in the format 0 + number. For example, 0142 ;
  • 16th number system in the format 0x + number. For example, 0x2F .

24, 030, 0x18 are all entries of the same number in different number systems.
To write floating point numbers, dot notation is used: 0.1, .5, 4. - either in
exponential notation - 25e-100. There should be no spaces in such a record.

The name with which we can associate the values ​​written by literals is called a variable. A variable is a named or otherwise addressable location in memory whose address can be used to access data. This data is written, overwritten and erased in memory in a certain way during the execution of the program. The variable allows you to access the data at any time and, if necessary, change them. Data that can be retrieved from a variable name is called the variable's value.
In order to use a variable in a program, it must be declared, and if necessary, it can be defined (= initialized). A variable declaration in the program text necessarily contains 2 parts: the base type and the declarator. The specifier and initializer are optional parts:

const int example = 3; // here const - specifier // int - base type // example - variable name // = 3 - initializer.

The variable name is a sequence of characters from letters of the Latin alphabet (lowercase and uppercase), numbers and/or underscores, but the first character cannot be a digit. The variable name should be chosen in such a way that it is always easy to guess what it stores, for example, "monthPayment". In the abstract and in practice, we will use the CamelCase notation for the rules for writing variables. The name of a variable cannot coincide with words reserved in the language, examples of such words: if, while, function, goto, switch, etc.

The declarator, in addition to the variable name, may contain additional characters:

  • * - pointer; before the name
  • *const - constant pointer; before the name
  • & - link; before the name
  • - array; after the name;
  • () - function; after the name.

An initializer allows you to define a variable's value immediately after the declaration. The initializer starts with an equals literal (=) and then the process of setting the value of the variable takes place. Generally speaking, the equal sign in C++ denotes an assignment operation; it can be used to set and change the value of a variable. It may be different for different types.

The specifier specifies additional attributes other than the type. The const specifier given in the example allows you to prohibit subsequent changes to the value of the variable. Such immutable variables are called constant or constant.

Declaring a constant without initialization will not work for logical reasons:

Const int EMPTY_CONST; // error, constant variable not initialized const int EXAMPLE = 2; // constant with value 2 EXAMPLE = 3; // error, attempt to assign a value to a constant variable

For naming constants, it is customary to use only uppercase letters, separating words with an underscore character.

Basic Data Types in C++

In dissecting each type, the reader must remember to define the data type.

1. Integer type (char, short(int), int, long(int), long long)

From the name it is easy to understand that the set of values ​​consists of integers. Also, the set of values ​​of each of the listed types can be signed (signed) or unsigned (unsigned). The number of elements contained in a set depends on the size of the memory that is used to store the value of that type. For example, for a variable of type char, 1 byte of memory is allocated, so the total elements will be:

  • 2 8N = 2 8 * 1 = 256, where N is the amount of memory in bytes to store the value

In such a case, the ranges of available integers are as follows:

  • - for unsigned char
  • [-128..127] - for signed char

By default, a variable of an integer type is considered signed. To indicate in the code that a variable should be unsigned, a signed sign is assigned to the base type on the left, i.e. unsigned:

unsigned long values; // defines an integer (long) unsigned type.

The listed types differ only in the amount of memory required for storage. Since the C++ language is a rather machine-specific language standard, it only guarantees the following condition:

  • 1 = char size ≤ short size ≤ int size ≤ long size.

Usually the sizes of types are as follows: char - 1, short - 2, int - 4, long - 8, long long - 8 bytes.

You can perform arithmetic operations with integer type values: +, -, *, /, %; comparison operations: ==, !=,<=, <, >, >=; bit operations: &, |, xor,<<, >>.
Most operations such as addition, multiplication, subtraction, and comparison operations are easy to understand. Sometimes, after performing arithmetic operations, the result may be outside the range of values; in this case the program will give an error.
Integer division (/) finds the integer part of dividing one integer by another. For example:

  • 6 / 4 = 1;
  • 2 / 5 = 0;
  • 8 / 2 = 4.

The percent symbol (%) denotes the operation of determining the remainder of the division of two integers:

  • 6 % 4 = 2;
  • 10 % 3 = 1.

More difficult to understand operations are bitwise: & (AND), | (OR), xor (exclusive OR),<< (побитовый сдвиг влево), >> (bitwise right shift).

Bit operations AND, OR and XOR apply the corresponding logical operation to each bit of information:

  • 1 10 = 01 2
  • 3 10 = 11 2
  • 1 10 & 3 10 = 01 2 & 11 2 = 01 2
  • 1 10 | 3 10 = 01 2 | 11 2 = 11 2
  • 1 10 xor 3 10 = 01 2 xor 11 2 = 10 2

In image processing, 3 channels are used for color: red, blue and green - plus transparency, which are stored in a variable of type int, because each channel has a range of values ​​from 0 to 255. In hexadecimal, a value is written as follows: 0x180013FF; then the value 18 16 corresponds to the red channel, 00 16 - blue, 13 16 - green, FF - alpha channel (transparency). To select a certain channel from such an integer, use the so-called. mask, where the positions of interest to us are F 16 or 1 2 . That is, to highlight the value of the blue channel, you must use a mask, i.e. bitwise AND:

int blue_channel = 0x180013FF & 0x00FF0000;

After that, the received value is shifted to the right by the required number of bits.

A bitwise shift shifts left or right as many bits of a number as specified on the right side of the operation. For example, the number 39 for the char type in binary form is written as follows: 00100111. Then:

Char binaryExample = 39; // 00100111 char result = binaryExample<< 2; // сдвигаем 2 бита влево, результат: 10011100

If the variable is of unsigned type, then the result will be the number 156, for a signed one it is equal to -100. Note that for signed integer types, the unit in the high order of the bit representation is a sign that the number is negative. In this case, a value in binary form consisting of all ones corresponds to -1; if 1 is only in the most significant digit, and the remaining digits are zeros, then such a number has the minimum value for a particular type of value: for char it is -128.

2. Floating point type (float, double (float))

The set of floating-point values ​​is a subset of real numbers, but not every real number can be represented in binary, which sometimes leads to stupid mistakes:

float value = 0.2; value == 0.2; // error, value will not be equal to 0.2 here.

When working with floating point variables, the programmer should not use the equality or inequality operation, instead they usually use a test to hit a certain interval:

Value - 0.2< 1e-6; // ok, подбирать интервал тоже нужно осторожно

In addition to comparison operations, the floating point type supports 4 arithmetic operations, which are fully consistent with mathematical operations with real numbers.

3. Boolean (logical) type (bool)

Consists of only two values: true (true) and false (false). To work with variables of this type, logical operations are used: ! (NOT), == (equality), != (inequality), && (logical AND), || (logical OR). The result of each operation can be found in the corresponding truth table. For example:

X Y XOR0 0 0 0 1 1 1 0 1 1 1 0

4. Character type (char, wchar_t)

The char type is not only an integer type (usually, such a type is called byte), but also a character type, storing the character number from the table as an ASCII character. For example, the code 0x41 corresponds to the character 'A', and 0x71 - 't'.

Sometimes it becomes necessary to use characters that are not fixed in the ASCII table and therefore require more than 1 byte to be stored. There is a wide character (wchar_t) for them.

5.1. Arrays

Arrays allow you to store a sequential set of elements of the same type. An array is stored in memory in a contiguous block, so you cannot declare an array without specifying its size. To declare an array, after the variable name write square brackets () indicating its size. For example:

int myArray; // Array of 5 elements of integer type

To initialize an array, the values ​​are listed in curly braces. You can only initialize in this way at the time of variable declaration. By the way, in this case it is not necessary to specify the size of the array:

int odds = (1, 3, 7, 9, 11); // The array is initialized with 5 values

To access a specific value in an array (array element), use the index access operation () with the element number (numbers start from 0). For example:

odds; // access to the first element of the array. Returns the value 1 odds; // access to the third element. Returns the value 7 odds = 13; // Assign a new value to the 5th element of the array odds; // access error

5.3. Strings

To write a string, programmers use the idea that a string is a consecutive series (array) of characters. To identify the end of a line, a special end-of-line character is used: '\0'. These special characters, consisting of a backslash and an identifying character, are called control or escape characters. There are still, for example, '\n' - the beginning of a new line, '\t' - tabulation. To record a backslash in a line, escaping is used - another slash is put before the sign itself: '\'. Escaping is also used to write quotation marks.

Let's create a string variable:

Char textExample = ('T', 'e', ​​'s', 't', '\0'); // the string "Test" is written

There is a simplified notation for string initialization:

Char textExample = "Test"; // The last character is not written, but the size is still 5

Without going into details, here is another useful data type - string. Strings
of this type, for example, you can add:

String hello = "Hi, "; stringname = "Max!"; string hello_name = hello + name; // Get the string "Hi, Max!"

6. Link

Int a = 2; // variable "a" points to value 2 int &b = a; // variable "b" points to the same place as "a" b = 4; // by changing the value of b, the programmer changes the value of a. Now a = 4 int &c = 4; // error, you can't do this, because reference cannot be assigned a value

7. Pointer

To deal with this type of data, it is necessary to remember that the set of values ​​of this type is the addresses of memory cells from where the data begins. The pointer also supports addition (+), subtraction (-), and dereferencing (*) operations.

Addresses 0x0 means that the pointer is empty, i.e. does not point to any data. This address has its own literal - NULL:

Int *nullPtr = NULL; // null pointer

Adding and subtracting an address with an integer or another address allows
move around the memory available to the program.

The operation of getting data starting at the address stored in a pointer is called dereferencing (*). The program reads the required number of memory cells and returns the value stored in memory.

Int valueInMemory = 2; // set a variable of integer type int *somePtr = // copy the address of the variable, here & - returns the address of the variable somePtr; // address of the memory cell, for example, 0x2F *somePtr; // value is stored in 4 cells: 0x2F, 0x30, 0x31 and 0x32

For pointers, the assignment operation, which is syntactically the same as the copy operation, is not available. In other words, you can copy the address of another pointer or the address of a variable, but you cannot determine the value of the address yourself.

The pointer itself is stored in memory, like the values ​​of variables of other types, and takes 4 bytes, so you can create a pointer to a pointer.

8. Transfers

Enumerations are the only basic type defined by the programmer. By and large, an enumeration is an ordered set of named integer constants, with the enumeration name being the base type.

Enumcolor(RED, BLUE, GREEN);

By default, RED = 0, BLUE = 1, GREEN = 2. Therefore, the values ​​can be compared with each other, i.e. RED< BLUE < GREEN. Программист при объявлении перечисления может самостоятельно задать значения каждой из констант:

Enum access(READ=1, WRITE=2, EXEC=4);

It is often convenient to use enumerations whose values ​​are a power of two, because in binary representation, a number that is a power of 2 will consist of the 1st unit and zeros. For example:

8 10 = 00001000 2

The result of adding these numbers together always clearly indicates which numbers were added:

37 10 = 00100101 2 = 00000001 2 + 00000100 2 + 00100000 2 = 1 10 + 4 10 + 32 10

Void

Syntactically, the void type is one of the fundamental types, but it can only be used as part of more complex types, because objects of type void do not exist. Typically, this type is used to inform that a function has no return value, or as the base type of a pointer to objects of undefined types:

void object; // error, there are no objects of type void void // error, there are no references to void void *ptr; // ok, store a pointer to an unknown type

Often we will use void specifically to indicate that a function does not return any value. A void type pointer is handled when the programmer takes full responsibility for memory integrity and correct type casting.

Cast

It is often necessary to cast the value of a variable of one type to another. In the case where the set of values ​​of the original type is a subset of a larger type (for example, int is a subset of long and long is a double), the compiler can implicitly ( implicitly) change the value type.

int integer = 2; floating floating = integer; // floating = 2.0

The type conversion will be performed with the loss of information, so only the integer part of the floating point number will remain, the fractional part will be lost.

There is the possibility of explicit (explicitly) type conversion, for this, to the left of the variable or some value of the original type, in parentheses, write the type to which the cast will be made:

int value = (int) 2.5;

Unary and binary operations

Those operations that we performed earlier are called binary: to the left and to the right of the operation symbol there are values ​​or variables, for example, 2 + 3. In addition to binary operations, programming languages ​​also use unary operations that apply to variables. They can be either to the left or to the right of a variable, several such operations have been encountered before - the dereference operation (*) and taking the address of a variable (&) are unary. Operators "++" and "-" increase and decrease the value of an integer variable by 1, respectively, and can be written either to the left or to the right of the variable.

C++ also uses a shorthand notation for binary operations when the left and right sides of an expression contain the same variable, i.e. some operation is performed with the value of the variable and the result of the operation is stored in the same variable:

A += 2; // same as a = a + 2; b /= 5; // same as b = b / 5; c &= 3; // same as c = c & 3;

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.

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. Because 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; }

IN 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). IN line 10 cout operator prints the character contained in the variable symbol . IN 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 amount of 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 considered 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

Editor's Choice
What kind of diet for diabetes, what is possible and what is not, a table of product properties - these concepts should be known and put into practice ...

Dream Interpretation of the 20th century If a person flies freely and easily in a dream, this means that fate itself opens the right road and takes care of the owner ...

Every year the number of patients with diabetes is increasing. To keep glucose levels within normal limits, you should observe ...

Despite the increased role of the Internet, books do not lose popularity. Knigov.ru has combined the achievements of the IT industry and the usual process...
The issue of Slavic runes disturbs the minds of people who study history, archeology, and magical practices. The ancient Slavs used runes in ...
Luck is a capricious person, however, every person needs it. People are trying in every way to keep her next to them, and if not ...
Yulia Alekseevna Caesar, hereditary witch. Tarologist. Runologist. Reiki Master. Written Articles For each person, his home is a reliable ...
In the Eastern tradition, the first chakra Muladhara or root chakra (other names: red chakra, survival chakra) is the base ...
Join us on Facebook We put our soul into our project No one will argue that seeing a bad dream is an alarming sign. However...