The path to C ++ primer (fifth edition)-Chapter 4: expressions, C Language

Source: Internet
Author: User

The path to C ++ primer (fifth edition)-Chapter 4: expressions, C Language

[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]


4.1 Basics


1. The expression is composed of one or more operation objects (operand). Evaluate the expression to get a result ). The literal value and variable are the simplest expressions, and the result is the literal value and variable value. A complex expression can be generated by combining an operator with one or more operation objects.


2. C ++ defines unary operator and binary operator ). The operator acting on an operation object is a unary operator, for example, the address operator (&) and the quote operator (*); The operator acting on two operation objects is a binary operator, such as equal operator (=) and multiplication operator (*). In addition, there is a three-element operator acting on three operation objects. Function calling is also a special operator that has no limit on the number of computing objects.
Some symbols can be used both as unary operators and binary operators. Take symbol * as an example. When it is used as a unary operator, the unreferenced operation is executed. When it is used as a binary operator, the multiplication operation is performed. Whether a symbol is a unary operator or binary operator is determined by its context. For this type of symbol, its two usage are irrelevant and can be regarded as two different symbols.


3. During the expression evaluation process, the calculation object is often converted from one type to another.


4. The C ++ language defines the operations performed by operators when they act on computation objects of built-in and composite types. When an operator acts on an operation object of the class type, you can define its meaning. This custom process actually gives another meaning to existing operators, so it is called overloaded operator ). The> and <operators of the IO library, and the operators used by string objects, vector objects, and iterators are both heavy-duty operators.


5. The expression of C ++ is either the right value (rvalue, read as "are-value") or the left value (lvalue, read as "ell-value ").
When an object is used as the right value, it uses the object value (content). When the object is used as the left value, it uses the Object Identity (location in memory ).


6. The final value of an expression depends on the combination of its subexpressions. The operation objects of high-priority operators are more closely combined than those of low-priority operators. If the priority is the same, the combination rules are determined by the combination law.


7. The following two empirical criteria are useful for writing compound expressions:
1. When you are not sure, it is best to use parentheses to force the combination of expressions to conform to the requirements of the program logic.
2. If you change the value of an operation object, do not use this operation object elsewhere in the expression.


4.2 Arithmetic Operators


1.



2. The operator %, commonly known as the "remainder" or "modulo" operator, is used to calculate the remainder obtained by Division of two integers. The operation object involved in the remainder operation must be of the integer type. The new C ++ 11 standard stipulates that all vendors should be rounded to 0 (that is, the fractional part is directly removed ).

Except for the special case where m causes overflow, (-m)/n and m/(-n) are all equal to-(m/n), m % (-n) equal to m % n, (-m) % n is equal to-(m % n ).


4.3 logical and Relational operators


1.



2. For logic and operators, evaluate the right operation object only when the left operation object is true.
For logic or operators, evaluate the right operation object only when the left operation object is false.


3. When performing a comparison operation, do not use true or false values as the calculation object unless the object to be compared is of the boolean type.


4.4 value assignment operator


1. Each operator has a composite value assignment form:

+ =-= * =/= % = // Arithmetic Operator <<=>>=<=^=|=// bitwise Operator

4.5 increment and decrease Operators


1. Addition operators (++) and subtraction operators () provide a simple form of writing for the operations of adding 1 and subtracting 1 to an object.


2. We recommend that you do not use the post version of the progressively decreasing operator unless required.

Readers who have a C language background may have doubts about the prefix increment operator. In fact, the reason is very simple: the increment operator of the prefix avoids unnecessary work, after adding the value to 1, it directly returns the changed operation object. In comparison, the post version needs to store the original value to return the unmodified content. If we do not need to modify the previous value, the post-version operation is a waste.
For integer and pointer types, the compiler may optimize such extra work. However, for relatively complex iterator types, this extra work consumes a lot. We recommend that you develop the habit of using the pre-version, so that you do not need to worry about performance issues, but more importantly, the written code will be more in line with the original programming intention.


4.6 Access operators for Members


1. vertex operators and arrow operators can be used to access members. vertex operators obtain a member of class objects. Arrow operators are related to vertex operators. The expression ptr-> mem is equivalent to (* ptr ). mem.


2. The Arrow operator acts on a pointer-type operation object and returns a left value. The vertex operator is divided into two situations: if the object to which the member belongs is the left value, the result is the left value; otherwise, if the object to which the member belongs is the right value, the result is the right value.


4.7 conditional Operators


1. Conditional operators (? :) Allow us to embed the simple if-else logic into a single expression, and use the conditional operators as follows:
Cond? Expr1: expr2;
Cond is the expression used to determine the condition, and expr1 and expr2 are two expressions of the same type or may be converted to a public type. The execution of conditional operators is: first evaluate the cond value. If the condition is true, evaluate expr1 and return this value; otherwise, execute expr2.


4.8-bit operator


1.



2. For bitwise AND operator (&), if the locations of the two calculation objects are both 1, the bitwise in the calculation result is 1; otherwise, the bitwise is 0. For bitwise OR operator (|), if at least one of the two calculation objects is 1, the bitwise is 1 in the calculation result; otherwise, the bitwise is 0. For bitwise XOR operators (^), if there is only one corresponding location of the Two Computing objects and one is 1, the bitwise is 1 in the calculation result; otherwise, the bitwise is 0.


4.9 sizeof Operator


1. the sizeof operator returns the number of bytes occupied by an expression or a type name. The sizeof operator satisfies the right Union law, and the obtained value is a constant expression of the size_t type.


2. The result of the sizeof operator is partly dependent on the type it applies:
Perform the sizeof operation on the expression of char or char type. The result is 1.
Perform the sizeof operation on the reference type to obtain the space occupied by the referenced object.
Execute the sizeof operation on the pointer to obtain the space occupied by the pointer.
Execute the sizeof operation on the unreferenced pointer to obtain the space occupied by the object to which the Pointer Points. the pointer does not need to be valid.
Execute the sizeof operation on the array to get the size of the space occupied by the entire array. It is equivalent to executing a sizeof operation on each element of the array and summation of the result. Note that the sizeof operation does not convert the array into a pointer.
Executing the sizeof operation on a string object or a vector object only returns the size of the fixed part of the type, and does not calculate the amount of space occupied by the elements in the object.


4.10 comma Operator


1. the comma operator (comma operator) contains two operation objects, which are evaluated in order from left to right. Like logical operators, logical operators, or conditional operators, the comma operator also specifies the order in which the values of the computing objects are evaluated.
For the comma operator, evaluate the expression on the left and discard the result. The true result of the comma operator is the value of the expression on the right. If the right operation object is a left value, the final result is also a left value.


4.11 type conversion


1. In the following cases, the compiler will automatically convert the type of the computing object:
In most expressions, integer values smaller than the int type are first upgraded to a larger Integer type.
In the condition, the non-Boolean value is converted to the boolean type.
During initialization, the initial value is converted to the type of the variable. In the value assignment statement, the right operation object is converted to the type of the Left operation object.
If there are multiple types of arithmetic operations or relational operations, you need to convert them to the same type.
Type conversion also occurs when the function is called.


2. A naming forced type conversion has the following forms:
Cast-name <type> (expression );
Here, type is the conversion target type and expression is the value to be converted. If type is a reference type, the result is the left value. Cast-name is one of static_cast, dynamic_cast, const_cast, and reinterpret_cast. Dynamic_cast supports runtime type recognition. Cast-name specifies the type of conversion to be executed.


3. static_cast can be used for any type conversion with a clearly defined definition, as long as it does not contain the underlying const.
Const_cast can only change the underlying const of an operation object.
Reinterpret_cast generally provides a re-interpretation at a lower level for the bitwise mode of the computing object.


4.12 operator priority table




PS: answers to some exercises


Practice 4.6

i % 2 == 0 ? "even" : "odd"

Practice 4.10

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

Practice 4.11

a > b && b > c && c > d


Practice 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;}


Practice 4.23

string pl = s + (s[s.size() - 1] == 's' ? "" : "s") ;

Practice 4.25

The result is 1111 1111 1111 1111 1110 0011 1000 0000

-7296 in decimal format


Practice 4.28

#include <iostream>using std::cout;using std::endl;int main(){cout << "bool\t\tis " << sizeof(bool) << "bytes." << endl;cout << "char\t\tis " << sizeof(char) << "bytes." << endl;cout << "wchar_t\t\tis " << sizeof(wchar_t) << "bytes." << endl;cout << "char16_t\tis " << sizeof(char16_t) << "bytes." << endl;cout << "char32_t\tis " << sizeof(char32_t) << "bytes." << endl;cout << "short\t\tis " << sizeof(short) << "bytes." << endl;cout << "int\t\tis " << sizeof(int) << "bytes." << endl;cout << "long\t\tis " << sizeof(long) << "bytes." << endl;cout << "long long\tis " << sizeof(long long) << "bytes." << endl;cout << "float\t\tis " << sizeof(float) << "bytes." << endl;cout << "double\t\tis " << sizeof(double) << "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);pv = &d;        // pv = static_cast<void*>(&d);pc = (char*)pv; // pc = reinterpret_cast<char*>(pv);


Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source

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.