"C++primer (fifth edition)" Learning Path-Chapter Fourth: expressions

Source: Internet
Author: User
Tags arithmetic operators bitwise bitwise operators

"Disclaimer: All rights reserved, please indicate the source of the reprint, do not use for commercial purposes. Contact mailbox: [Email protected] "


4.1 Basics


1. The expression consists of one or more operands (operand) that evaluates the expression to give a result. Literals and variables are the simplest expressions (expression), and the result is the value of literals and variables. Combining an operator (operator) with one or more operands can produce more complex expressions.


2.c++ defines a unary operator (unary operator) and a two-tuple operator (binary operator). An operator that acts on an operand is a unary operator, such as a fetch address (&) and a dereference (*), and an operator that acts on two operands is a two-tuple operator, such as the equality operator (= =) and the multiplication operator (*). In addition, there is a ternary operator that acts on three operands. A function call is also a special operator that has no limit on the number of operands.
Some symbols can be used as a unary operator as well as a two-dollar operator. Take the symbol * As an example, perform a multiply operation as a unary operator when the dereference operation is performed as a two-tuple operator. Whether a symbol is a unary operator or a two-tuple operator is determined by its context. For this type of notation, its two usages are irrelevant and can be used as two different symbols.


3. During the evaluation of an expression, an operand is often converted from one type to another.


The 4.c++ language defines the operations that operators perform when operating on built-in types and compound types. When an operator acts on an operand of a class type, the user can define its own meaning. Because this custom process actually assigns another layer of meaning to an existing operator, it is called an overloaded operator (overloaded operator). The >> and << operators of the IO Library, as well as the operators used by string objects, vector objects, and iterators, are overloaded operators.


The expression of 5.c++ is otherwise rvalue (rvalue, read as "Are-value"), otherwise the lvalue (Lvalue, read as "Ell-value").
When an object is used as an rvalue, the object's value (content) is used, and when the object is used as an lvalue, the object's identity (in-memory position) is used.


6. The final value of the expression depends on how its sub-expressions are combined. Operands of high-priority operators are more tightly grouped than operands of lower-precedence operators. If the precedence is the same, the combination rule is determined by the binding law.


7. The following two rules of thumb are useful for writing composite expressions:
1. When in doubt, it is best to use parentheses to force the composition of the expression to conform to the requirements of the program logic.
2. If you change the value of an operand, do not use the operand anywhere else in the expression.


4.2 Arithmetic operators


1.



2. Operator% commonly known as "take the remainder" or "modulo" operator, is responsible for the calculation of the remainder of two integers, the operand involved in the remainder operation must be an integer type. The new C++11 standard stipulates that the quotient shall be rounded to 0 (i.e. direct resection of the minor part).

In addition to the special case where m causes overflow, other times (-m)/N and m/(-N) are equal-(m/n), m% (-N) equals m%n, (-m)%n equals-(m%n).


4.3 Logical AND relational operators


1.



2. For logic and operators, the right operand is evaluated only when the left operand is true.
For a logical OR operator, the right operand is evaluated only when the left operand is false.


3. Do not use Boolean literals true and false as operands unless the object being compared is a Boolean type for comparison operations.


4.4 Assignment operators


1. Each operator has a corresponding compound assignment form:

+ =      =      *=      /=      %=  //arithmetic operator  <<= >>=  &= ^= |= Bitwise operators

4.5 Increment and decrement operators


1. The increment operator (+ +) and decrement operator () provide a concise form of writing for an object's addition of 1 and minus 1 operations.


2. Recommendation: Do not increment the post-build of the decrement operator unless necessary

Readers with a C-language background may have questions about the precedence of using the predecessor version increment operator, in fact the reason is very simple: the predecessor version of the increment operator avoids unnecessary work, and it adds 1 to return the changed operand directly. In contrast, the post-build needs to store the original values for easy return to the unmodified content. If we do not need to modify the previous value, then the operation of the post-version is a waste.
For integers and pointer types, the compiler might optimize this extra work, but for relatively complex types of iterators, this extra work is expensive. It is recommended that you develop the habit of using a predecessor version, so that you do not need to worry about performance issues, but more importantly, the code you write will be more consistent with your programming intentions.


4.6 Member access operators


1. Both the dot operator and the arrow operator can be used to access the member, where the point operator gets a member of the class object, and the arrow operator is related to the point operator, and the expression Ptr->mem equivalent to (*ptr). Mem.


2. The arrow operator acts on a pointer-type operand, and the result is an lvalue. The point operator is divided into two cases: if the object to which the member belongs is an lvalue, then the result is an lvalue, and conversely, if the object to which the member belongs is an rvalue, the result is the right value.


4.7 Bar Operators


1. The conditional operator (? :) allows us to embed simple if-else logic into a single expression, and the conditional operator is used in the following form:
Cond? EXPR1:EXPR2;
Where cond is the expression that determines the condition, and Expr1 and EXPR2 are two expressions of the same type or may be converted to a public type. The conditional operator is executed by first seeking the value of cond, or EXPR2 if the condition is true for EXPR1 and returns the value.


4.8-bit operators


1.



2. For Bits and operators (&), if the corresponding position of the two operands is 1, the bit is 1 in the result of the operation, otherwise 0. For a bitwise OR operator (|), if the corresponding position of two operands has at least one of 1, the bit in the result of the operation is 1, otherwise 0. For the bitwise XOR operator (^), if the corresponding position of the two operands has only one of 1, the bit is 1 in the result of the operation, otherwise 0.


4.9 sizeof operator


The 1.sizeof operator returns the number of bytes that an expression or a type name occupies. The sizeof operator satisfies the right-associative law, and the resulting value is a constant expression of type size_t.


The result of the 2.sizeof operator is partially dependent on the type of action:
The sizeof operation is performed on a char or an expression of type char, resulting in 1.
Performs a sizeof operation on a reference type to get the size of the space occupied by the referenced object.
Performing a sizeof operation on a pointer gets the size of the space occupied by the pointer itself.
Performing the sizeof operation on the dereference pointer gets the size of the space occupied by the object pointed to by the pointer, and the pointer does not need to be valid.
Performing the sizeof operation on an array results in the size of the space occupied by the entire arrays, which is equivalent to performing the sizeof operation once for all elements in the logarithm and summing the resulting result. Note that the sizeof operation does not convert the array into pointers for processing.
Performing a sizeof operation on a string object or a vector object returns only the size of the fixed part of the type, and does not calculate how much space the elements in the object occupy.


4.10 comma operator


1. The comma operator (comma operator) contains two operands, evaluated sequentially from left to right. Like logical and logical or conditional operators, the comma operator also specifies the order in which operands are evaluated.
For the comma operator, the expression on the left is evaluated first, and then the evaluation result is discarded. The true result of the comma operator is the value of the right-hand expression. If the right operand is an lvalue, the final evaluation result is also an lvalue.


4.11 Type Conversions


1. In these cases, the compiler automatically converts the type of the operand:
In most expressions, an integer value that is smaller than the int type is first promoted to a larger integer type.
In a condition, a non-Boolean value is converted to a Boolean type.
During initialization, the initial value is converted to the type of the variable, and in the assignment statement, the right operand is converted to the type of the left operand.
If the operands of an arithmetic or relational operation have multiple types, they need to be converted to the same type.
A type conversion also occurs when a function is called.


2. A named coercion type conversion has the following form:
cast-name<type> (expression);
Where type is the target type of the conversion and expression is the value to be converted. If type is a reference type, the result is an lvalue. Cast-name is one of the static_cast, dynamic_cast, Const_cast and reinterpret_cast. Dynamic_cast supports run-time type recognition. CAST-NAME specifies what kind of conversion is performed.


3. Any well-defined type conversion, as long as it does not contain the underlying const, can use static_cast.
Const_cast can only change the underlying const of an operand.
Reinterpret_cast usually provides a lower level of re-interpretation of the bitwise patterns of the operands.


4.12 Operator Precedence Table




PS: Part of the exercise answer


Exercise 4.6

I% 2 = = 0? "Even": "Odd"

Exercise 4.10

int i = 0;while (cin >> i && i! = 42)

Exercise 4.11

a > B && b > C && C > D


Exercise 4.21

#include <iostream> #include <vector>using std::cin;using std::cout;using std::endl;using std::vector;int Main () {vector<int> num {1,2,3,4,5,6,7,8,9,10};for (auto &c:num) {if (c%2) c = c*2;} for (auto C:num) Cout<<c<<endl;}


Exercise 4.23

String PL = s + (S[s.size ()-1] = = ' s '? "": "S");

Exercise 4.25

The result of the binary is 1111 1111 1111 1111 1110 0011 1000 0000

Decimal representation is-7296


Exercise 4.28

#include <iostream>using std::cout;using std::endl;int main () {cout << ' bool\t\tis ' << sizeof (BOOL) & lt;< "bytes." << endl;cout << "Char\t\tis" << sizeof (char) << "bytes." << Endl;cout < < "Wchar_t\t\tis" << sizeof (wchar_t) << "bytes." << endl;cout << "Char16_t\tis" << size Of (char16_t) << "bytes." << endl;cout << "Char32_t\tis" << sizeof (char32_t) << "bytes." &lt ;< endl;cout << "Short\t\tis" << sizeof (short) << "bytes." << endl;cout << "Int\t\tis" << sizeof (int) << "bytes." << endl;cout << "Long\t\tis" << sizeof (long) << "bytes." & lt;< endl;cout << "Long Long\tis" << sizeof (Long long) << "bytes." << endl;cout << "Floa T\t\tis "<< sizeof (float) <<" bytes "<< endl;cout <<" Double\t\tis "<< sizeof (double) &lt ;< "bytes." << EndL;cout << "Long Double\tis" << sizeof (long double) << "bytes." << endl;cout << Endl;return 0;}

Practice 4.36

I *= static_cast<int> (d);

Practice 4.37

int i; Double D; const string *ps; Char *pc; void *PV;PV = (void*) PS; PV = const_cast<string*> (PS); or PV = static_cast<void*> (const_cast<string*> (PS)); i = int (*pc);   i = static_cast<int> (*pc);p v = &d;        PV = static_cast<void*> (&d);p C = (char*) PV; PC = Reinterpret_cast<char*> (PV);


Copyright NOTICE: This article is the original blogger article, if reproduced, please indicate the source

"C++primer (fifth edition)" Learning Path-Chapter Fourth: expressions

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.