Contacts

What is more with or c. Relation operators and logical operators. Operations for integer computing

Since in the previous article, I first used a logical operation, I will tell you what they are, how many and how they use them.

In C ++, there are three logical operations:

  1. Logical operation and &&, we are already known;
  2. Logic operation or || ;
  3. Logic operation ne. ! or logical denial.

Logical operations form a complex (composite) condition from several simple (two or more) conditions. These operations simplify the structure software code several times. Yes, you can do without them, but then the number of IFOs increases several times, depending on the condition. The following table briefly described all logical operations in the C ++ programming language to build logical conditions.

Now you should understand the difference between logical operation And and a logical operation or to not be confused in the future. It's time to get acquainted with the data type BOOL -Logic. This type Data can take two values: True (Truth) and False. The condition checked in the selection operators has a BOOL data type. Consider the principle of operation of the next program, and everything will be understood with all these logical operations.

// or_and_not.cpp: Specifies the input point for the console application. #Include "stdafx.h" #include Using Namespace STD; Int Main (int argc, char * argv) (Bool A1 \u003d True, A2 \u003d false; // Announcement of logical variables BOOL A3 \u003d TRUE, A4 \u003d FALSE; COUT<< "Tablica istinnosti log operacii &&" << endl; cout << "true && false: " << (a1 && a2) << endl // логическое И << "false && true: " << (a2 && a1) << endl << "true && true: " << (a1 && a3) << endl << "false && false: " << (a2 && a4) << endl; cout << "Tablica istinnosti log operacii ||" << endl; cout << "true || false: " << (a1 || a2) << endl // логическое ИЛИ << "false || true: " << (a2 || a1) << endl << "true || true: " << (a1 || a3) << endl << "false || false: " << (a2 || a4) << endl; cout << "Tablica istinnosti log operacii !" << endl; cout << "!true: " << (! a1) << endl // логическое НЕ << "!false: "<< (! a2) << endl; system("pause"); return 0; }

Rows 9 and 10 You must be understood, as variables type are initialized here. BOOL . And each variable is assigned the value True or False. Beginning with 9th row And finishing 20-y.The use of logical operations is shown. The result of the program (see Figure 1).

Tablica Istinnosti log operacii && true && false: 0 false && True: 0 True && True: 1 False && False: 0 Tablica Istinnosti log Operacii || True || False: 1 false || True: 1 True || True: 1 False || False: 0 Tablica Istinnosti Log Operacii! ! True: 0! False: 1 To continue, press any key. . .

Figure 1 - Logic Operations C ++

Probably, you have a question, "what are these testers and units?". If there is a question, then you need to answer. I answer: "Nolik is a representation of the logical value of False (lies), but the units are a logical true (truth)." Briefly explain some moments. Compound Condition using logical AND True only when both simple conditions are true. In all other cases, the composite condition is false. Compound Condition using logical or falsely only when false both simple conditions. In all other cases, the composite condition is true. Logical denial NOT is a unary operation, and it does not combine two conditions, unlike logical operations AND and ORwhich are binary operations. Logical denial allows you to flip the meaning of the condition that in some cases it is very convenient. The condition with a logical denial is true if the same condition is false without negative, and vice versa.

In the text in any natural language, you can select four main elements: symbols, words, phrases and suggestions. The algorithmic language also contains such elements, only words are called lexemes (elementary structures), phrases - expressions, offers - operators. The lexemes are formed from symbols, expressions from lexemes and symbols, operators from expressions and lexing symbols (Fig. 1.1)

Fig. 1.1. The composition of the algorithmic language

Thus, the elements of the algorithmic language are:

1) Alphabet Language C ++, which includes

- Capital and lowercase Latin letters and an underscore sign;

- Arabic numbers from 0 to 9;

- Special signs "(), | () + - /% *. \\ ':; &?<>=!#^

- Blind symbols (gap, tab symbol, transition symbols to a new string).

2) Language lexemes are formed from characters:

Identifiers - Names of C-program objects. Latin letters, numbers and an underscore sign can be used in the identifier. Capital and lowercase letters differ, for example, Prog1, Prog1 and Prog1 are three different identifiers. The first character should be the letter or underscore (but not a figure). Spaces in identifiers are not allowed.

Key (reserved) words are words that have a special value for the compiler. They cannot be used as identifiers.

- Signs of operations are one or more characters that determine the action on the operands. Operations are divided into unary, binary and ternar in the number of operands participating in this operation.

Constants- These are immutable values. There are integer, real, symbolic and string constants. The compiler highlights the constant as a lexeme (elementary design) and relates it to one of the types according to its appearance.

Dividers - brackets, dot, comma space icons.

CONSTANTS IN C ++

Constant - This is a lexeme representing an image of a fixed numerical, string or symbolic value.

Constants are divided into 5 groups:

- real (floating point);

- listed;

- symbolic;

- String.

The compiler selects a lex and relates it to a particular group, and then inside the group to a specific type on its form of recording in the text of the program and by numerical value.

Constants can be decimal, octal and hexadecimal. The decimal constant is defined as a sequence of decimal digits, which starts not from 0, if this is not 0 (examples: 8, 0, 192345). The octal constant is a constant that always begins with 0. In 0 follows the octal numbers (examples: 016 - decimal value 14, 01). Hex constants are a sequence of hexadecimal numbers that precede the characters 0x or 0x (examples: 0ha, 0x00f).

Depending on the value of the entire constant, the compiler will present it in different ways to the computer's memory (i.e. the compiler will appear the corresponding data type constant).

Real constants have another form of internal presentation in the memory of the computer. The compiler recognizes such constants according to their form. Real constants can have two form forms: with a fixed point and floating point. Fixed Point Constant View: [Figures]. [Figures] (examples: 5.7, .0001, 41.). View of a floating point constant: [Figures] [.] [Figures] E | E [+ | -] [Figures ] (Examples: 0.5e5, .11e-5, 5e3). In the recording of real constants, either a whole, or fractional part, or a decimal point, or a sign of exponentials with an indicator of the extent can be lowered.

Enumerated constants are entered using the Enum keyword. These are common entire constants that are unique and convenient to use the designation are attributed. Examples: enum (one \u003d 1, two \u003d 2, three \u003d 3, FOUR \u003d 4);

enum (Zero, One, Two, Three) - If in defining listed constants omit signs \u003d and numeric values, then the values \u200b\u200bwill be attributed to the default. In this case, the very left identifier will receive a value of 0, and each subsequent will increase by 1.

enum (Ten \u003d 10, Three \u003d 3, Four, Five, Six);

enum (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);

Symbolic constants are one or two characters enclosed in apostrophes. Symbolic constants consisting of one symbol have a type of char and occupy one byte in memory, character constants consisting of two characters have the type int and occupy two bytes. The sequences starting with the sign \\ are called managers, they are used:

- To represent characters that do not have a graphical display, for example:

\\ A - beep,

\\ b - Return one step,

\\ n - Row translation,

\\ T - horizontal tab.

- for the presentation of characters: \\, ',? , "(\\\\, \\ ', \\?, \\").

- To represent characters with hexadecimal or octal codes (\\ 073, \\ 0xF5).

The string constant is a sequence of characters enclosed in quotes. Inside the rows can also use control characters. For example: "\\ Nnoving string",

"\\ N \\" Algorithmic Languages \u200b\u200bof High Level Programming \\ "".

Types of data in C ++

The data is displayed in the program around the world. The goal of the program is to process data. Data different types are stored and processed in different ways. Data type determines:

1) an internal representation of data in the computer's memory;

2) a lot of values \u200b\u200bthat can take values \u200b\u200bof this type;

3) operations and functions that can be applied to data of this type.

Depending on the requirements of the job, the programmer selects the type for program objects. Types of C ++ can be divided into simple and composite. Simple types include types that are characterized by one value. In C ++, 6 simple data types are defined:

There are 4 type specifiers specifying the internal representation and range of standard types

short (short)

lONG (long)

signed (sign)

unsigned (unsightened)

A typeint.

The values \u200b\u200bof this type are integers.

The size of type int is not determined by the standard, but depends on the computer and compiler. For a 16-bit processor, 2 bytes are assigned to it, for 32-bit - 4 bytes.

If the SHORT specifier is standing before INT, then 2 bytes are given to the number, and if the LONG specifier, then 4 bytes. From the number of assigned to the memory object, the many valid values \u200b\u200bthat may receive an object depends:

short int - occupies 2 bytes, therefore, has a range -32768 .. + 32767;

lONG INT - ranks 4 bytes, therefore, has a range -2 147 483 648 .. + 2 147 483 647

The INT type coincides with the SHORT INT type on 16-bit PCs and with Long int the 32-bit PC.

Signed and Unsigned modifiers also affect the set of permissible values \u200b\u200bthat the object can take:

unsigned short int - occupies 2 bytes, therefore, has a range of 0 ..65536;

unsigned long int - ranks 4 bytes, therefore, has a range of 0 .. + 4 294 967 295.

A typechar.

The values \u200b\u200bof this type are the elements of the final ordered set of characters. Each character is put in accordance with the number called the symbol code. Under the size of the symbol type 1 byte is given. Char type can be used with Signed and unsigned specifiers. In these Signed CHAR type, you can store values \u200b\u200bin the range from -128 to 127. When using the Unsigned CHAR type, the values \u200b\u200bcan be in the range from 0 to 255. The ASCII code is used for encoding (American Standard Code Foe International Interchange). Symbols with codes from 0 to 31 are service and have an independent value only in I / O statements.

CHAR type values \u200b\u200bare also used to store numbers from the specified ranges.

A typewchar_t.

Designed to work with a set of characters for encoding which is not enough by 1 byte, such as Unicode. The size of this type, as a rule, corresponds to the type of Short. The string constants of this type are recorded with the prefix L: L "String # 1".

A typebOOL

The BOOL type is called logical. Its values \u200b\u200bcan take True and False values. The internal form of representation FALSE is 0, any other value is interpreted as true.

Floating point types.

The internal representation of the real number consists of 2 parts: mantissa and order. In IBM-compatible PC, the size of the Float type is occupied by 4 bytes, of which one discharge is taken under the sign of the mantissa, 8 discharges under the order and 24 - under the Mantissa.

The values \u200b\u200bof the Types of Double occupy 8 bytes, 11 and 52 discharge are discharged under the order and mantissa, respectively. The length of the mantissa determines the accuracy of the number, and the length of its range.

If there is a LONG specifier in front of the Double type name, then bytes are given under the magnitude.

A typevoid.

The main types also includes the Void type many values \u200b\u200bof this type - empty.

Variables

The variable in C ++ is a named memory area in which data is stored. The variable has a name and value. The name serves to refer to the memory area in which the value is stored. Before use, any variable must be described. Examples:

General view of the description of the description:

[memory class] type name [initializer];

Memory class can take values: Auto, Extern, Static, Register. The memory class determines the lifetime and scope of the variable. If the memory class is not explicitly specified, the compiler determines its on the basis of the ad context. Living time can be permanent - during the execution of the program or temporary - during the block. Scope - part of the text of the program from which we assume the usual access to the variable. Usually the scope of visibility coincides with the area of \u200b\u200baction. In addition, the case when there is a variable in the internal block with the same name.

Const - indicates that this variable cannot be changed (named constant).

When you describe, you can assign an initial value variable (initialization).

Memory classes:

aUTO -Automatic local variable. The AUTO specifier can only be specified when determining the block objects, for example, in the body function. This variable memory is released at the input to the unit and is released when exiting it. Outside the block, such variables do not exist.

extern is a global variable, it is in another place of the program (in another file or share in the text). Used to create variables that are available in all program files.

static is a static variable, it exists only within the limits of the file where the variable is defined.

register is similar to AUTO, but the memory is allocated in the processor registers. If there is no such possibility, the variables are processed as AUTO.

Int a; // Global variable void main () (int b; // Local variable external int x; // variable x is defined elsewhere static int c; // Local static variable A \u003d 1; // Assigning a global variable int A; / / Local variable A A \u003d 2; // Assigning a local variable :: a \u003d 3; // Assigning a global variable) int x \u003d 4; // Definition and initialization x

In the example, the variable A is determined outside of all blocks. The action area of \u200b\u200bthe variable A is the entire program, except for those rows where the local variable A is used. Variables B and C - local, the area of \u200b\u200btheir visibility is a block. Living lifetime: Memory under B is released when entering the block (since by default, the AUTO memory class) is released when exiting it. A variable with (static) exists while the program works.

If, when determining the initial value, the variables are not specified explicitly, then the compiler reset global and static variables. Automatic variables are not initialized ..

The name of the variable should be unique in its field of action.

The description of the variable can be completed or as an ad, or as definition. The ad contains information about the memory class and type of variable, the definition along with this information gives an indication to allocate memory. In the example of Extern Int X; - Announcement, and the rest - definitions.

SI /+ operations signs

Signs of operations ensure the formation of expressions. Expressions consist of operands, signs of operations and brackets. Each operand is, in turn, the expression or private case of expressions is a constant or variable.

Unary operations

& getting Operand Address
* Appeal to the address (Range)
unary minus, changes the sign of the arithmetic operand
~ discontinuous inverting of the internal binary code of integer operand (bitwise denial)
! logical denial (not). As logic values, 0 - false and not 0 - truth, denial 0 will be 1, the denial of any non-zero number will be 0.
++ Increase by one:

prefix operation - increases the operand to its use,

the postfix operation increases the operand after its use.

int a \u003d (m ++) + n; // a \u003d 4, m \u003d 2, n \u003d 2

int b \u003d m + (++ n); // a \u003d 3, m \u003d 1, n \u003d 3

— — reducing per unit:

prefix operation - reduces operands before use,

the postfix operation reduces the operand after its use.

sizeof calculation of size (in bytes) for the object of that type, which has an operand

he has two forms

sizeof Expression

sizeof (Float) // 4

sizeOF (1.0) // 8, because the default real constants have a type of double

Binary operations.

Additive:

Multiplicative:

Shift operations (defined only for integer operands).

Expression format with shift operation:

operand_Shel Operand Operand Operand

Digit operations:

Comparison Operations: The result is true (not 0) or FALSE (0)

Logic binary operations:

Assignment operations

Etc.

Operations format simple assignment:

operand1 \u003d Operand2

The left-flowing value (L-value) is an expression that addresses some section of the memory, i.e. it can be added to it. This name has happened from the assignment operation, since the left part of the assignment operation is determined which the operation of the operation will be entered into what area of \u200b\u200bmemory. The variable is a special case of a lesive expression.

Conditional operation.

Unlike unary and binary operations, it uses three operands.

Expression1? Expression2: expression3;

The first is the value of the expression1. If it is true, the value of the expression2 is calculated, which becomes the result. If, when calculating the expression1, it turns out 0, then the expression value is taken as a result.

For example:

x.<0 ? -x: x ; //вычисляется абсолютное значение x.

Operation of explicit (conversion) type of type.

There are two forms: canonical and functional:

1) (Name) Operand

2) Type_name (Operand)

(int) a // canonical form

iNT (A) // Functional form

Expressions

From constants, variables, separators and operations of operations can be designing expressions. Each expression is a rule of calculating a new value .. If the expression generates an integer or real number, then it is called arithmetic. A pair of arithmetic expressions, combined with a comparison operation, is called an attitude. If the ratio has a non-zero value, then it is true, otherwise - false.

Priorities of operations in expressions

Rank Operations
1 () -> .
2 ! ~ - ++ - & * (Type) Sizeof Type ()
3 * /% (multiplicative binary)
+ - (additive binary)
5 << >\u003e (bonnetic shift)
6 < > <= >\u003d (Relationship)
7 \u003d\u003d! \u003d (Relationship)
8 & (bonding conjunction "and")
9 ^ (Figure excluding "or")
10 | (Diajunction "or")
11 && (conjunction "and")
12 || (disjunction "or")
13 ?: (conditional operation)
14 = *= /= %= -= &= ^= |= <<= >\u003e \u003d (assignment operation)
15 , (comma operation)

Last updated: 06/19/2017

A separate set of operations is conditional expressions. Such operations return a logical value, that is, the value of type BOOL: TRUE, if the expression is truly, and false, if the expression is false. Such operations include comparison and logical operations.

Operations of comparison

In the comparison operations, two operands are compared and the value of type BOOL is true, if the expression is true, and FALSE, if the expression is incorrect.

    Compare two operands for equality. If they are equal, then the operation returns True, if not equal, then False is returned:

    B; // False

    Compare two operands and returns TRUE if the operands are not equal, and false, if they are equal.

    Int a \u003d 10; int b \u003d 4; BOOL C \u003d A! \u003d B; // True Bool D \u003d a! \u003d 10; // False

    Operation "Less than". Returns TRUE if the first operand is less than the second, and false, if the first operand is greater than the second:

    Int a \u003d 10; int b \u003d 4; BOOL C \u003d A< b; // false

    Operation "More than". Compare two operands and returns true if the first operand is more than the second, otherwise returns FALSE:

    Int a \u003d 10; int b \u003d 4; BOOL C \u003d A\u003e B; // True Bool d \u003d a\u003e 25; // False

    Operation "less or equal." Compares two operands and returns TRUE if the first operand is less or equal to the second. Otherwise returns False.

    Int a \u003d 10; int b \u003d 4; BOOL C \u003d A<= b; // false bool d = a <= 25; // true

    Operation "greater than or equal." Compare two operands and returns true if the first operand is greater than or equal to the second one, otherwise FALSE is returned:

    Int a \u003d 10; int b \u003d 4; BOOL C \u003d A\u003e \u003d B; // True Bool D \u003d A\u003e \u003d 25; // False

Operations<, > <=, >\u003d have a greater priority than \u003d\u003d and! \u003d.

Logical operations

Also in C # defined logical operators, which also return the value of the BOOL type. As operands, they take the value of the BOOL. As a rule, apply to relationships and combine several comparison operations.

    Operation of logical addition or logical or. Returns True if at least one of the operands returns TRUE.

    Bool x1 \u003d (5\u003e 6) | (four< 6); // 5 > 6 - FALSE, 4< 6 - true, поэтому возвращается true bool x2 = (5 > 6) | (4\u003e 6); // 5\u003e 6 - False, 4\u003e

    Operation of logical multiplication or logical I. Returns TRUE if both operands are simultaneously equal to TRUE.

    BOOL X1 \u003d (5\u003e 6) & (4< 6); // 5 > 6 - FALSE, 4< 6 - true, поэтому возвращается false bool x2 = (5 < 6) & (4 < 6); // 5 < 6 - true, 4 < 6 - true, поэтому возвращается true

    Operation of logical addition. Returns True if at least one of the operands returns TRUE.

    BOOL X1 \u003d (5\u003e 6) || (four< 6); // 5 > 6 - FALSE, 4< 6 - true, поэтому возвращается true bool x2 = (5 > 6) || (4\u003e 6); // 5\u003e 6 - FALSE, 4\u003e 6 \u200b\u200b- FALSE, so False returns

    Operation of logical multiplication. Returns True if both operands are true at the same time.

    BOOL X1 \u003d (5\u003e 6) && (4< 6); // 5 > 6 - FALSE, 4< 6 - true, поэтому возвращается false bool x2 = (5 < 6) && (4 < 6); // 5 < 6 - true, 4 < 6 - true, поэтому возвращается true

    Operation of logical denial. It is performed above one operand and returns TRUE if the operand is false. If the operand is true, the operation returns FALSE:

    BOOL A \u003d TRUE; BOOL B \u003d! A; // False

    Operation excluding or. Returns True if either the first or second operand (but not at the same time) are true, otherwise returns false

    BOOL X5 \u003d (5\u003e 6) ^ (4< 6); // 5 > 6 - FALSE, 4< 6 - true, поэтому возвращается true bool x6 = (50 > 6) ^ (4 / 2 < 3); // 50 > 6 - True, 4/2< 3 - true, поэтому возвращается false

Here we have two pairs of operations | and || (as well as & &&) perform similar actions, but they are not equivalent.

In the expression z \u003d x | y; Both values \u200b\u200bwill be calculated - x and y.

In the expression z \u003d x || y; First, the value of X will first be calculated, and if it is true, the calculation of the value of y does not make sense, since in any case, Z will be equal to True. The value of Y will be calculated only if the X is equal to FALSE

The same applies to pair of operations & / &&. In the expression z \u003d x, both values \u200b\u200bwill be calculated - x and y.

In the expression z \u003d x & will first be calculated x, and if it is equal to false, the calculation of the value of y does not make sense, since in any case, Z will be equal to False. Y value will only be calculated if x is true

Therefore, operations || and && are more convenient in calculations, as it allows you to reduce the time for calculating the value of the expression, and thereby increase productivity. And operations | and & are more suitable for the execution of biddling operations over numbers.

Relation operators and logical operators

In the notation operator of the relationship and logical operator term relations means the relationship that may exist between two values, and the term logical - the relationship between the logical values \u200b\u200bof "Truth" and "Lie". And since the operators of the relationship give true or false results, they are often used together with logical operators. It is for this reason that they are considered jointly.

Below are the relationship operators:

The logical includes operators below:

The result of the execution of the operator of the relationship or logical operator is the logical value of the BOOL type.

In general, objects can be compared to equality or inequality using the relationship operators \u003d\u003d and! \u003d. And the comparison operators, \u003d can be used only to the data types that support the order ratio. Consequently, relational operators can be applied to all numeric data types. But the BOOL type values \u200b\u200bcan only be compared to equality or inequality, since true (true) and false (false) values \u200b\u200bare not ordered. For example, the comparison of True\u003e False in C # does not make sense.

Consider an example of a program demonstrating the use of relations and logical operators:

Using SYSTEM; using system.collections.Genic; Using System.linq; Using System.Text; Namespace ConsoleApplication1 (String Args (STRING VOID D \u003d 10, F \u003d 12; BOOL VAR1 \u003d TRUE, VAR2 \u003d FALSE; if (df) Console.WriteLine ("D\u003e F"); // comparing Variables VAR1 and VAR2 if (VAR1 & VAR2) Console.WriteLine ("This text will not disable"); if (! (VAR1 & VAR2)) Console.Writeline ("! (VAR1 & VAR2) \u003d TRUE"); if (var1 | VAR2) Console.Writeline ("var1 | var2 \u003d true"); if (var1 ^ var2) console.writeline ("var1 ^ var2 \u003d true"); console.ReadLine ();)))

Logical operators in C # perform the most common logical operations. Nevertheless, there are a number of operations performed by the rules of formal logic. These logical operations can be built using logical operators supported in C #. Consequently, in C # there is such a set of logical operators, which is sufficient to build almost any logical operation, including implications. Amplication - This is a binary operation, the result of which is a false value only if its left operand has a true meaning, and the right one is false. (The implication operation reflects the following principle: Truth cannot imply a lie.)

The implication operation can be built on the basis of a combination of logical operators! and |:

Shortened logical operators

C # also has special, shortening, options for logical operators and or, designed to obtain a more efficient code. Let us explain in the following examples of logical operations. If the first operand of a logical operation and has a false value (false), then its result will have a false value regardless of the value of the second operand. If the first operand of a logical operation or has a true value (true), then its result will have a true value regardless of the value of the second operand. Due to the fact that the value of the second operand in these operations does not need to be calculated, saves time and increases the efficiency of the code.

A shortened logical operation and is performed using operator &&, and a shortened logical operation or - with operator ||. These shortened logical operators correspond to ordinary logical operators & and |. The only difference between the shortened logical operator from the usual lies in the fact that its second operand is calculated only as needed.

Any expression of the language consists of operands (variables, constants, etc.) connected by the signs of operations. Operation sign is a symbol or group of characters that report compiler about the need to perform certain arithmetic, logical or other actions.

Operations are performed in a strict sequence. The value that determines the preemptive right to perform a particular operation is called priority. In tab. 2 Listed various operations of the SI (C) language. Their priorities for each group are the same (groups are highlighted by color). The greater advantage the corresponding group of operations is used, the higher it is located in the table. The procedure for performing operations can be regulated using parentheses.

Table 2 - Operations

Sign of operation

Purpose of the operation

Call function

Allocation of the element of the array

Selecting the entry element

Selecting the entry element

Logical denial

Digital denial

Change of sign

Equality per unit

Reduction by unit

Taking the address

Appeal to address

Type conversion (i.e. (Float) a)

Determining size in bytes

Multiplication

Determination of the balance

Addition

Subtraction

Shift left

Shift to the right

Less than

Less or equal

More than

More or equal

Loan logical "and"

Digit excluding "or"

Loan logical "or"

Logical "and"

Logical "or"

Conditional (Ternar) Operation

Assignment

+=, - =, *=, /=, %=, <<=,
>>=, &=, |=, ^=

Binary operations (for example, a * \u003d b
(i.e. a \u003d a * b), etc.)

Operation comma

Operator in SI (C)

To exclude confusion in the concepts of "Operation" and "Operator", we note that the operator is the smallest executable unit of the program. The expression operators are distinguished, the action of which consists in calculating the specified expressions (for example: a \u003d sin (b) + C; j ++;), ad operators, composite operators, empty operators, label operators, cycle, etc. To refer to the end of the operator in the SI (C) language, a point is used. As for the composite operator (or block), which is a set of logically related operators placed between opening (() and closing ()) curly brackets ("operator brackets"), then the point with a comma is not put. Note that the block differs from the composite operator by the presence of definitions in the body of the block.

Characteristics of the main operations of the SI language (C)

We characterize the basic operations of the SI (C) language.

Assignment operation

First, consider one of them - the assignment operation (\u003d). Expression of type

assigns the variable x value of the variable y. Operation "\u003d" is allowed to use multiple times in one expression, for example:

x \u003d y \u003d z \u003d 100;

Distinguish unary and binary operations. In the first of these, one operand, and the second - two. Let's start their consideration from operations related to the first of the following traditional groups:

Arithmetic operations.

Logic operations and relations relationships.

Operations with bits.

Arithmetic operations are set by the following symbols (Table 2): +, -, *, /,%. The last one cannot be applied to a variable of real type. For example:

a \u003d b + c;
x \u003d y - z;
R \u003d T * V;
s \u003d k / l;
P \u003d Q% W;

Logical operations

Logical Relationship Operations are set by the following symbols (see Table 2): && ("and"), || ("OR"), ! ("Not"),\u003e,\u003e \u003d,<, <= , = = (равно), != (не равно). Традиционно эти операции должны давать одно из двух значений: истину или ложь. В языке СИ (C)принято следующее правило: истина - это любое ненулевое значение; ложь - это нулевое значение. Выражения, использующие логические операции и операции отношения, возвращают 0 для ложного значения и 1 для истинного. Ниже приводится таблица истинности для логических операций.

Bit operations can be applied to variables that have INT, CHAR types, as well as their variants (for example, LONG INT). They cannot be applied to variable types of Float, Double, Void (or more complex types). These operations are set by the following symbols: ~ (bonnetal denial),<< (сдвиг влево), >\u003e (shift to the right), & (bonnet "and"), ^ (bits excluding "or"), | (Digit "or").

Examples: if a \u003d 0000 1111 and b \u003d 1000 1000, then

~ a \u003d 1111 0000,
A.<< 1 = 0001 1110,
A \u003e\u003e 1 \u003d 0000 0111,
A & B \u003d 0000 1000,
a ^ b \u003d 1000 0111,
a | B \u003d 1000 1111.

The language provides for two non-traditional increment operations (++) and decrement (-). They are designed to increase and decrease the operand value. Operation ++ and - can be recorded both in front of the operand and after it. In the first case (++ n or --n), the operand value (N) changes before its use in the appropriate expression, and in the second (N ++ or N--) - after its use. Consider the following two rows of the program:

a \u003d b + C ++;
a1 \u003d b1 +++ C1;

Suppose that B \u003d B1 \u003d 2, C \u003d C1 \u003d 4. Then after performing operations: A \u003d 6, B \u003d 2, C \u003d 5, A1 \u003d 7, B1 \u003d 2, C1 \u003d 5.

Expressions with another non-traditional ternary or conditional operation are widespread. In the formula

y \u003d A, if x is not zero (i.e., true), and y \u003d b, if x is zero (false). Next expression

y \u003d (a\u003e b)? A: B;

allows you to assign a variable in the value of a greater variable (A or B), i.e. y \u003d max (a, b).

Another distinction of the language is that the expression of the form a \u003d a + 5; can be written in another form: a + \u003d 5;. Instead of a sign + you can use the symbols of other binary operations (see Table 2).

Other Table operations. 2 will be described in subsequent paragraphs.

Cycles are organized to perform some operator or group of operators a certain number of times. In the SI (C) language, three cycle operators: for, While and Do - While. The first of them is formally written, in the following form:

for (expression_1; expression_2; expression_3) Body_TSikla

The cycle body is either one operator, or several operators enclosed in curly brackets (...) (after the block point with a comma is not placed). In expressions 1, 2, 3 appears a special variable called the control. By its value, the need to repetition cycle or exit from it is established.

Expression_1 assigns the initial value of the control variable, the expression_s changes it at each step, and the expression_2 checks whether it has reached the boundary value that establishes the need to exit the cycle.

for (i \u003d 1; i< 10; i++)

for (Сh \u003d "a"; ch! \u003d "p";) scanf ("% c", & ch);

/ * Cycle will be executed until the keyboard

the symbol "P" * /

Any of three expressions in the FOR cycle may be absent, however, the point with a comma should remain. Thus, for (;;) (...) is an infinite cycle, from which you can exit only in other ways.

In the SI (C) language, the following rule is taken. Any expression with an assignment operation enclosed in parentheses is equal to assigned. For example, the expression (A \u003d 7 + 2) is 9. After that, you can write another expression, for example: ((A \u003d 7 + 2)<10), которое в данном случае будет всегда давать истинное значение. Следующая конструкция:

((SH \u003d getch ()) \u003d\u003d "I")

allows you to enter the value of the CH variable and give the true result only when the value entered is the letter "I". In brackets, you can record several formulas constituting a complex expression. For these purposes, the comma operation is used. Formulas will be calculated from left to right, and all expression will take the value of the last calculated formula. For example, if there are two variables of type char, then expression

z \u003d (x \u003d y, y \u003d getch ());

defines the following actions: The value of the variable y is assigned to the variable x; A symbol from the keyboard is introduced and assigned to the variable y; z Gets the value of the variable y. The brackets are needed here, since the comma operation has a lower priority than the assignment operation recorded after the Z variable. The comma operation is widely used to build the FOR cycle expressions and allows you to simultaneously change the values \u200b\u200bof several control variables.

Invested structures are allowed, i.e. In the body of some cycle, other FOR operators may occur.

The WHILE statement is formally written in this form:

while (expression) body_TSikla

The expression in brackets can take non-zero (true) or zero (false) value. If it is truly, the cycle body is performed and the expression is calculated again. If the expression is false, then the While cycle ends.

The DO-WHILE statement is formally written as follows:

do (Body_Cyklla) While (expression);

The main difference between the WHILE and DO - WHILE cycles is that the body in the DO - WHILE cycle is performed at least once. The cycle body will be performed until the expression in brackets will take a false value. If it is false when entering the cycle, its body is performed exactly once.

The nesting of some cycles to others is allowed, i.e. In the body of any cycle, Operators for, While and DO - While can appear.

In the body of the cycle, new Break and Continue operators can be used. The BREAK operator provides an immediate output from the cycle, the Continue operator causes the termination of the next and the beginning of the next iteration.

Conditional and unconditional transition operators

To organize conditional and unconditional transitions in the SI (C) program (c), operators are used: if - ELSE, Switch and Goto. The first one is written as follows:

if (check_linking) operator_1; ELSE operator_2;

If the condition in brackets takes the true value, the operator_1 is performed if the false operator_2. If instead of one you need to perform several operators, then they are curly braces. In the IF statement, the word ELSE may be absent.

In the IF - ELSE statement directly after the IF and ELSE keywords must follow other operators. If at least one of them is an IF operator, it is called invested. According to the agreement adopted in the SI (C) agreement, the word ELSE always refers to the nearest IF prior to it.

The SWITCH operator allows you to choose one of several alternatives. It is written in the following formal form:

switch (expression)

case Constanta_1: Operators_1;

case Constanta_2: Operators_2;

........ ........

dEFAULT: Operators_Default;

Here the value of a whole expression in brackets is calculated (it is sometimes called the selector) and it is compared with all constants (constant expressions). All constants must be different. When matching, an appropriate version of the operators (one or more operators) is executed. An option with a key word default is implemented if no other approached (the word default may be missing). If default is absent, and all the results of the comparison are negative, then no option is performed.

To stop follow-up checks after a successful choice of some option, the Break operator is used, providing an immediate output from the Switch switch.

Invested Switch designs.

Consider the rules for performing an unconditional transition that can be submitted in the following form:

goto label;

The label is any identifier after which the colon is delivered. The Goto operator indicates that the program must be continued from the operator, before which the label is recorded. The label can be put in front of any operator in the function where the GOTO operator corresponds to it. It should not be announced.

Turbo debugger fully supports the syntax of the expressions of the SI (C) expressions. The expression consists of a mixture of operations, strings, variables



Did you like the article? Share it