C ++ (2): operator, expression, and operator expression

Source: Internet
Author: User
Tags bitwise operators

C ++ (2): operator, expression, and operator expression

C ++ Operator

C ++ has rich operators, making C ++ operations very flexible and convenient. For example, assign a value (=) as an operator. In this way, a = B = c = 4 is a legal expression, which is different from other languages. C ++ provides the following operators:

  1. Arithmetic Operators
    + (Plus)-(minus) * (multiplication)/(Division) % (Division for remainder) + + (self-addition) -- (auto-subtraction)
  2. Relational operators
    > (Greater than) <(less than) = (equal to) >=( greater than or equal to) <= (less than or equal )! = (Not equal)
  3. Logical operators
    & (Logical and) | (logical or )! (Non-logical)
  4. Bitwise operators
    <(Shift left by bit)> (shift right by bit) & (shift by bit and) | (shift by bit or) ^ (shift by bit or )~ (Bitwise inversion)
  5. Value assignment operator (= and its extended value assignment operator)
  6. Conditional operators (? :)
  7. Comma operator (,)
  8. Pointer operator (*)
  9. Reference operators and address operators (&)
  10. Sizeof)
  11. Forced type conversion operator (type) or type ())
  12. Member operator (.)
  13. Operator pointing to a member (->)
  14. Subscript operator ([])
  15. Others (such as function call operators ())
C ++ Arithmetic Operators and basic arithmetic operators of arithmetic expressions This chapter mainly introduces Arithmetic Operators and arithmetic expressions, value assignment operators and value assignment expressions, comma operators and comma expressions, other operators will be introduced in subsequent chapters.

Common Arithmetic Operators
Operator Description Example
+ Addition operator or positive operator 3 + 5, + 3
- Subtraction operator or negative value operator 5-2,-3
* Multiplication Operator 3*5
/ Division Operator 5/3
% Modulo operator, or equality operator % Both sides should be integer data, for example, the value of 7% 4 is 3

It must be noted that the result of division of two integers is an integer. For example, if the result value of 5/3 is 1, the decimal part is removed. However, if either the divisor or the divisor is a negative value, the rounding direction is not fixed. For example,-5/3 gets result-1 on some C ++ systems, and some C ++ systems give result-2. Most compilation systems adopt the "rounded to zero" method, that is, 5/3 of the value is equal to 1,-5/3 of the value is equal to-1, and then rounded up to zero.

If one of the +,-, *,/operations is float data, the calculation result is double, because C ++ processes all float data in double mode During computation.
The priority and associativity of arithmetic expressions and operators the formula that connects the calculation object (also called the operand) with arithmetic operators and parentheses and complies with the C ++ syntax rules, it is called a C ++ arithmetic expression. Calculation objects include constants, variables, and functions. For example, the following is a valid C ++ arithmetic expression:
A * B/c-1.5 + 'A'

The C ++ language specifies the priority and combination of operators. When solving an expression, it is first executed in the order of priority of the operator, for example, first multiplication, division, and addition and subtraction. If expression a-B * c is used, the left side of expression B is minus sign, and the right side is a multiplication number. The multiplication number takes precedence over minus sign. Therefore, it is equivalent to a-(B * c ). If the operators on both sides of an operation object have the same priority level, for example, a-B + c, they are processed in the specified "integration direction.

C ++ specifies the combination direction (associativity) of various operators. The combination direction of arithmetic operators is "from left to right", that is, first left and then right. Therefore, B is first combined with minus signs, execute the-B operation, and then execute the plus c operation. "Link from left to right" is also called "link from left", that is, the calculation object is first combined with the operator on the left. You can see that the Union direction of some operators is "from right to left", that is, the right combination (for example, the value assignment operator ). The concept of "associativity" is not available in some other advanced languages and is one of the features of C and C ++.

For more information about all operators in C ++ and their priority and associativity, see the C ++ operator priority table.
The mixed operation between various types of numeric data in an expression is often performed between different types of data in an expression, for example:
10 + 'A' + 1.5-8765.1234 * 'B'
During calculation, data of different types must be converted to the same type before calculation. The conversion rules are shown in Figure 2.7.


Fig 2.7
Assume that I is specified as an integer variable, f is a float variable, d is a double variable, and e is a long variable. The following expression is provided:
10 + 'A' + I * f-d/e
Operation Order:
  1. Perform the 10 + 'A' operation. Convert 'A' to an integer 97 and the calculation result is 107.
  2. Perform the I * f operation. Convert both I and f to double type, and the calculation result is double type.
  3. The product of integer 107 and I * f is added. First, convert the integer 107 to the Double Precision (add a number of zeros after the decimal point, that is, 107.000... 00). The result is double.
  4. Convert variable e to double type, and result d/e is double type.
  5. Subtract the result of 10 + 'A' + I * f from the quotient of d/e, and the result is of the double type.
The above type conversion is automatically performed by the system. C ++ auto-increment and auto-subtraction operators (-- and ++) in C and C ++, the auto-increment (++) and auto-Subtract (--) operators are often used in expressions, their role is to increase or decrease the value of a variable by 1, for example:
++ I (before using I, add 1 to the value of I. If the original value of I is 3, run j = ++ I and set the value of j to 4)
-- I (before using I, first reduce the value of I by 1. If the original value of I is 3, then after j = -- I is executed, the value of j is 2)
I ++ (after I is used, add 1 to the value of I. If the original value of I is 3, after j = I ++ is executed, the value of j is 3, then I changes to 4)
I -- (after I is used, reduce the value of I by 1. If the original value of I is 3, after j = I -- is executed, the value of j is 3, then I changes to 2)
++ I executes I = I + 1 first and then uses the I value. I ++ uses the I value first and then executes I = I + 1.

Correct use of ++ and -- can make the program concise, clear, and efficient. Note:
  1. The auto-increment (++) and auto-increment (--) operators can only be used for variables, but not constants or expressions.
  2. The combination direction of ++ and -- is "from right to left ".
  3. The auto-increment (++) and auto-increment (--) operators are flexible to use, but in many cases there may be ambiguity, resulting in "unexpected" side effects.
  4. The auto-increment (subtraction) operator is often seen in C ++ programs. It is often used in loop statements to automatically add 1 to the variable. It is also used for pointer variables to point the pointer to the next address.
C ++ forced type conversion: data of different types in the expression is automatically converted to the type for calculation. Sometimes programmers can use the force type conversion operator to convert an expression to the desired type. For example:
(Double) a (convert a to double type)
(Int) (x + y) (convert the value of x + y to an integer)
(Float) (5% 3) (convert the value of 5% 3 to the float type)

The general form of forced type conversion is:
(Type name) (expression)

Note: If the object for forced type conversion is a variable, the variable can be enclosed in parentheses. If the object to be forced type conversion is an expression that contains multiple numbers, the expression should be enclosed in parentheses. If you write
(Int) x + y
Convert x to an integer and then add it to y.

The above forced type conversion is the original form of C language, C ++ retains it to facilitate compatibility. C ++ also adds the following forms:
Type name (expression)
For example
Int (x)
Or
Int (x + y)

Type names are not enclosed in parentheses, and variables or expressions are enclosed in parentheses. This form is similar to function call. However, many people are still accustomed to using the first form to enclose the type name in brackets, which makes it clearer.

It must be noted that an intermediate variable of the required type is obtained during forced type conversion, but the type of the original variable has not changed. For example:
(Int) x
If x is originally designated as the float type and the value is 3.6, an intermediate variable of the int type is obtained after the forced type operation. Its value is 3, and the original type and value of x remain unchanged.

(Example 2.4) Forced type conversion.
#include <iostream>using namespace std;int main( ){  float x;  int i;  x=3.6;  i=(int)x;  cout<<"x="<<x<<",i="<< i<<endl;  return 0;}
The running result is as follows:
X = 3.6, I = 3
The x type is still float and the value is still equal to 3.6.

We can see that there are two types of conversions. One is the type conversion that is automatically performed by the system, for example, 3 + 6.5, which does not need to be specified during operation. The second is forced type conversion. When automatic type conversion cannot be achieved, you can use forced type conversion. In addition, when calling a function, you can use the forced type conversion operator to obtain a parameter of the required type to make the actual participation parameter type consistent.
The C ++ assignment operator and the assignment expression assignment operator "=" are the assignment operator, which assigns data to a variable. For example, "a = 3" is used to perform a value assignment operation (or value assignment ). Assign constant 3 to variable. You can also assign the value of an expression to a variable.
During the value assignment process, if the types on both sides of the value assignment operator are inconsistent, but both are numeric or numeric, the type conversion is automatically performed during the value assignment.

1) when the floating point data (including Single and Double Precision) is assigned to an integer variable, the fractional part is discarded.

2) When the integer data is assigned to the floating point variable, the value remains unchanged, but is stored in the variable in exponential form.

3) when assigning a double type data to a float variable, note that the value range cannot overflow.

4) The character type data is assigned to the integer variable, and the ASCII code of the character is assigned to the integer variable.

5) assign an int, short, or long type data to a char type variable, and send it to the char type variable (truncation) only when its 8-bit low ). For example
Short int I = 289;
Char c;
C = I; // assign an int type data to a char type variable
The assignment is shown in Figure 2.8. For convenience, we can describe the situation that an int data occupies two bytes (16 bits.


Fig 2.8
6) Assign signed data to unsigned variables with the same length, copy the content of the storage unit as it is (even the original symbol bit is also transmitted as a numerical value ).

[Example 2.5] transfers signed data to unsigned variables.
#include <iostream>using namespace std;int main( ){  unsigned short a;  short int b=-1;  a=b;  cout<<"a="<<a<<endl;  return 0;}
The running result is
A = 65535

If the value assigned to B is-1, how can we get 65535? See the value assignment in Figure 2.9.


Fig 2.9
The complement of-1 is in the form of 1111111111111111 (that is, all 16 binary bits are 1), which is sent to a, and a is a signed variable, all 16 digits 1 is 65535 in decimal format. If B is positive ~ Between 32767, the value is not changed after the value is assigned.

The assignment of values between different types of integer data is ultimately one: directly transmitted in the form of storage in the storage unit.

C and C ++ are flexible to use. When values are assigned between different types of data, unexpected results are often returned, while the compilation system does not prompt errors. It depends on the programmer's experience to find out the problem. This requires programmers to understand the cause of the problem so that they can quickly troubleshoot the problem.
The composite value assignment operator can be a composite operator by adding other operators before the value assignment operator "=. If a "+" operator is added before "=", it becomes a compound operator "+ = ". For example, you can have
A + = 3 is equivalent to a = a + 3
X * = y + 8 is equivalent to x = x * (y + 8)
X % = 3 is equivalent to x = x % 3
Taking "a + = 3" as an example, it is equivalent to making a perform an auto-increment 3 operation. That is, add a 3 first and then assign it to. Similarly, "x * = y + 8" is used to multiply x by (y + 8) and then assign it to x.

To make it easier to remember, you can understand it as follows:
  1. A + = B (where a is a variable and B is an expression)
  2. A + = B (move the underlined "a +" to the right of "=)
  3. A = a + B (add variable name a on the left side of "=)

Note that if expression B contains several items, it is equivalent to brackets. For example
  1. X % = y + 3
  2. X % = (y + 3)
  3. X = x % (y + 3) (do not mistakenly think that x = x % y + 3)

Any binary (Binary) operator can be combined with a value assignment to form a composite value assignment. C ++ can use the following compound assignment operators:
+ =,-=, * =,/=, % =, <=, >>=, & =, ^ =, | =
The last five are bit operations.

C ++ uses this composite operator to simplify the program and refine the program, and to improve the compilation efficiency (this method is consistent with the "inverse Polish" method, which is conducive to compilation, can generate high-quality target code ). Professional programmers often use compound operators in programs. Beginners may not get used to them or use them less or less.
The expression used by the value assignment operator to connect a variable with an expression is called a value assignment expression ". It generally takes the following form:
<Variable> <value assignment operator> <expression>
For example, "a = 5" is a value assignment expression. The process of solving the value assignment expression is: first evaluate the value of the "expression" on the right of the value assignment operator, and then assign it to the variable on the left of the value assignment operator. An expression should have a value. The identifier on the left of the value assignment operator is called "left value" (left value, abbreviated as lvalue ). Not all objects can be left values, but variables can be left values. Expressions a + B cannot be left values, and constant variables cannot be left values, because constant variables cannot be assigned values.

The expression displayed on the right of the value assignment operator is called "right value" (rvalue ). Obviously, the left value can also appear on the right side of the value assignment operator, so the left value can be used as the right value. For example:
Int a = 3, B, c;
B = a; // B is the left value.
C = B; // B is also the right value
The "expression" in the value assignment expression can also be a value assignment expression. For example
A = (B = 5)
The following is an example of a value assignment expression:
A = B = c = 5 (values of the value assignment expressions are 5, a, B, and c are 5)
A = 5 + (c = 6) (expression value: 11, a value: 11, c value: 6)
A = (B = 4) + (c = 6) (expression value is 10, a value is 10, B is 4, c is 6)
A = (B = 10)/(c = 2) (expression value 5, a equals 5, B equals 10, c equals 2)
Analyze the following value assignment expression:
(A = 3*5) = 4*3
Brackets should be added when the value assignment expression is used as the left value. If it is written as follows, a syntax error will occur:
A = 3*5 = 4*3
Because 3*5 is not the left value, it cannot appear on the left side of the value assignment operator.

The value assignment expression can also contain compound value assignment operators. For example
A + = a-= a *
It is also a value assignment expression. If the initial value of a is 12, the procedure for solving the assignment expression is as follows:
  1. Perform the "a-= a * a" operation first, which is equivalent to a = a-a * a = 12-144 =-132.
  2. Then perform the "a + =-132" operation, which is equivalent to a = a + (-132) =-132-132 =-264.
The C ++ comma operator and the comma expression C ++ use the value assignment expression as an expression, so that the value assignment operation can not only appear in the value assignment statement, it can also appear in other statements (such as output statements and loop statements) in the form of expressions. This is a manifestation of the flexibility of the C ++ language.

Note that when you use a cout statement to output the value of a value assignment expression, you must enclose the value assignment expression in parentheses if it is written as "cout <a = B;.

C ++ provides a special operator, the comma operator. Use it to connect two expressions. For example
3 + 5, 6 + 8
It is also known as a comma expression and an ordered value operator ". The comma expression is generally in the following format:
Expression 1, expression 2
The process of solving a comma expression is: first solving expression 1, then solving expression 2. The value of the entire comma expression is the value of expression 2. For example, a comma expression
A = 3*5, a * 4
The priority of the value assignment operator is higher than that of the comma operator. Therefore, a = 3*5 (that is, "a = 3*5" as an expression) should be solved first ). After calculation and assignment, the value of a is 15, and then a * 4 is obtained, and 60 is obtained. The value of the entire comma expression is 60.

A comma expression can form a new comma expression with another expression, such
(A = 3*5, a * 4), a + 5
The general form of a comma expression can be extended:
Expression 1, expression 2, expression 3 ,..., Expression n
Its value is the value of expression n.

The comma operator is the lowest among all operators. Therefore, the following two expressions have different functions:
X = (a = 3, 6*3)
X = a = 3, 6 *

In fact, the comma expression is nothing more than concatenating several expressions. In many cases, the purpose of using a comma expression is to obtain the values of each expression separately, rather than necessarily obtaining and using the values of the entire comma expression, comma expressions are most commonly used in loop statements (for statements.

When you use cout to output the value of a comma expression, you must enclose the comma expression in parentheses, for example:
Cout <(3*5, 43-6*5, 67/3) <endl;

Strong expression ability in C and C ++ languages. One of the important aspects is its rich expression types and strong operator functions. Therefore, it is flexible and adaptable.







C language Experiment 2 data types, operators, expressions, and sequence expressions

1. # include <stdio. h> main () {int x, y, z; float arev; printf ("Enter three integers separated by spaces: \ n "); scanf ("% d", & x, & y, & z); arev = (float) (x + y + z)/3 ); printf ("mean: % f", arev);} 2. # inlcude <stdio. h> main () {int temp, a, B; printf ("enter two integers separated by spaces: \ n"); scanf ("% d ", & a, & B); printf ("a = % d, B = % d", a, B); a = temp; B = a; B = tem; printf ("loss of A, B value, a = % d, B = % B", a, B);} 3. if you do not score, you will not do the third question first.

What are C language operators? What do they mean? What is the purpose?

I. assignment operators
A value assignment statement is used to assign values of a constant, variable, or expression to another variable. The symbol is '= '. Here is not equal to, but a value is equal to '=.
Note: variables on the left of the value assignment statement must be declared elsewhere in the program.
The assigned variables are called left values because they appear on the left of the assignment statement. The generated values are called right values because they appear on the right of the assignment statement. A constant can only be used as the right value.
For example:
Count = 5;
Total1 = total2 = 0;
You can understand the first assignment statement.
The second value assignment statement assigns 0 values to two variables at the same time. This is because the value assignment statement is calculated from the right to the left, that is, from the right end. In this way, it first total2 = 0; then total1 = total2; then we can't do this?
(Total1 = total2) = 0;
This is not acceptable because total1 = total2 is an expression, and the expression is not allowed on the left of the value assignment statement.

Ii. Arithmetic Operators
In C, there are two single-eye and five binary operators.
Symbol function
+ Single lens
-Single Object negative
* Multiplication
/Division
% Modulo
+ Addition
-Subtraction
The following is an example of a value assignment statement. The above arithmetic operator is used in the expression on the right of the value assignment operator:
Area = Height * Width;
Num = num1 + num2/num3-num4;
The operator also has an operation order problem. Calculate the multiplication, division, and addition and subtraction first. The first operation is performed between a single object and a single object.
The modulo operator (%) is used to calculate the remainder obtained by Division of two integers. For example:
A = 7% 4;
In the end, the result of a is 3, because the remainder of 7% 4 is 3.
So what should I do if I want to ask their vendors?
B = 7/4;
In this way, B is their business. It should be 1.
Maybe someone doesn't understand. 7/4 should be 1.75. How can it be 1? It must be noted that when two integers are separated, the result is still an integer with no decimal part. To get the decimal part, you can write 7.0/4 or 7/4. 0 in this way, that is, change one of them to a non-integer.
So how can we get the integer part of a real number? This requires forced type conversion. For example:
A = (int) (7.0/4 );
Because the value of 7.0/4 is 1.75, if you add (int) to the front, the result is forcibly converted to an integer, and 1 is returned. Think about a = (float) (7/4); what is the final result of?
The single-object subtraction operator is equivalent to taking the opposite value. If it is positive, it becomes negative, and if it is negative, it becomes positive.
The single-object addition operator has no meaning. It is purely used with the single-object subtraction operator.

Iii. logical operators
Logical operators return true or false values based on the value of the expression. In fact, there is no so-called true value or false value in C language, but it is considered that non-0 is the true value, and 0 is the false value.
Symbol function
& Logic and
| Logical or
! Non-logical
For example:
5! 3;
0 |-2 & 5;
! 4;

When an & operation is performed on an expression, if one of the expressions is false, the total expression is false. The formula is true only when all expressions are true. When the expression performs | operation, the total value is true if one of them is true. The formula is false only when all values are false. Non-logical (!) The operation is to convert the corresponding variable data to the corresponding true/false values. If the original value is false, the logic is not true afterwards. If the original value is true, the logic is not false afterwards.
It is also very important that when the value of the last part of a logical expression does not affect the value of the entire expression, the latter part will not be computed. For example:
A = 2, B = 1;
A | B-1;
Because a = 2, is the true value, so no matter whether the B-1 is the true value, the total expression must be the true value, then the following expression will not calculate.

Iv. Relational operators
The relational operator compares two expressions and returns a true result.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.