Deepen the understanding of C language

We use a simple c program example to introduce the basic composition, format, and good writing style of C language, deepen the understanding of C language.

Example 1: c program to calculate the sum of two integers:

#include main() { int a,b,sum; /* Define variable a,b,sum to integer variable */ a=20; /* Assign integer 20 to integer variable a*/ b=15; /* Assign the integer 15 to the integer variable b*/sum=a+b; /* Assign the sum of two numbers to the integer variable sum*/printf (“a=%d,b =%d,sum=%d”,a,b,sum); /*Output the result to the display*/ }

Highlights:

1, any c language program must include the following format:

Main() { }

This is the basic structure of the C language. Any program must include this structure. Nothing can be written in parentheses, then the program will not perform any result.

2, main () - in the c language called "main function", a c program has only one main function, any c program is always started from the main function, the main function behind a pair of Parentheses cannot be omitted.

3. The content enclosed in braces {} is called the function body of the main function. This part of the content is what the computer wants to execute.

4. There is a semicolon (;) after each sentence in {}, and in c, we call a statement ending in a semicolon as a statement in c, and a semicolon is the end of the statement.

5, printf ("a =% d, b =% d, sum =% d", a, b, sum); ---- Through the implementation of this c language system provides us with a direct use of the screen output function, the user You can see the result of the operation. After the program runs, the following results will be displayed on the display:

a=20, b=15, sum=35

6, # include

Note: (1) Begin with # (2) Do not end with semicolon This line does not have a semicolon, so it is not a statement. It is called a command line in C language, or it is called "pre-compilation processing command".

7. Parts of the program that begin with /* and end with */ indicate the comment part of the program. Comments can be added anywhere in the program. They are added to improve the readability of the program, but the computer completely ignores the contents of the main function. The comment section, in other words, the computer as part of the comment does not exist in the main function.

C program generation process

C program is first compiled by the source file to generate the target file, and then through the connection to generate an executable file.

The source program has a .c extension, the target program has an .obj extension, and the executable program has an .exe extension.

Identifier

When writing programs, you must name functions, variables, etc. This name is called an identifier. The rules for naming identifiers in the C language are as follows:

The identifier can only consist of letters, numbers, and underscores;

The first letter of the identifier must be a letter and an underscore;

Identifiers are case-sensitive letters, such as If and if are two completely different identifiers.

The legal identifiers are as follows: A6, b_3, _mn Illegal identifiers are as follows: ab#12, 8m, tr3:4, yes no

The identifier cannot be the same as a keyword with special meaning in the program, and cannot be the same as the function name or C language library function prepared by the user. Various identifiers in the program should not be repeated so as to distinguish them. When selecting variable names and other identifiers, you should pay attention to "know names".

The identifiers are divided into the following three categories:

1, keywords

A keyword is a type of identifier that has a specific meaning and is used to specify a specific component of the C language. It cannot be used as an identifier for a user.

Auto break case char union do double else enum extern goto if int long short signed static sizof struct switch unsigned void for while typedef Continue float return typedef default

2, pre-defined identifier

Predefined identifiers also have a specific meaning in the C language, but they can be used as user identifiers. Predefined identifiers fall into two categories:

(1) Library function names, such as (printf, scanf, sin, isdigit, etc.) (2) Compiler processing command names, such as (define, include)

3, the user identifier

The user-defined identifiers are called user identifiers. Regardless of how an identifier is customized, it must conform to the three naming conventions for identifiers.

constant

In programs running, the amount whose value cannot be changed is called a constant. There are five types of constants: integer constants, real constants, character constants, string constants, and symbolic constants.

(a) Numerical conversion

The four expressions of numbers:

1: Binary: All digits are composed of 0,1, and every two digits will not appear in the binary digits. Example: 110101 2: Octal: Start with the number 0 (note that it is not the letter O, o), all the numbers are composed of 0~7, and there will be no 8 in the octal number every eight digits. Examples: 0112, 0123, 077, etc. 3: Decimal: All numbers are composed of 0~9, and every tenth and one decimal place do not appear in the decimal number. Example: 0,12, -15, etc. 4: Hexadecimal: Start with 0x or 0X (the number 0 plus the letter x), all numbers are made up of 0~9, A~F (or a~f), every Sixteen into one (where A, B, C, D, E, F represent 10, 11, 12, 13, 14, 15 respectively) Examples: 0x4A, 0X14c7, etc.

Inside the computer, the numbers are represented and stored in binary format. The ordinary decimal numbers entered by the user must be converted into binary by the computer before they can be stored in the computer. The computational result of the same computer is also binary, and it is generally converted to a decimal number. The output is read to the user, and this conversion is usually done automatically by the computer.

(1) Convert decimal to binary, octal, and hexadecimal

Divide: Divide the decimal number by 2 and record the remainder. The resulting quotient continues to divide by 2 until the quotient is 0. Then the remainders from each phase are arranged in reverse order from the back to the front. The resulting remainder digit sequence is the corresponding decimal number. Binary number. The octal and hexadecimal conversion methods are the same as above.

Example: The decimal number 13 is converted to a binary number of 1101, the conversion octal is 015, and converted to hexadecimal to D.

(2) Convert binary, octal, and hexadecimal to decimal

Product Sum: Each bit of the binary is multiplied by 20, 21, 22 from low to high (right low, left high). . . . , and then sum these sums.

For example: (1101)2=(13)10 (317)8=(207)10 (23E)16=(574)10

(3) Interchange between binary and octal, hexadecimal numbers

1: binary to octal: from right to left every three bits into a decimal number, the resulting data combination is the corresponding octal number (Note: the high position less than three zeros). Example: (010 110 111)2=(267)8 2: Binary to Hexadecimal: Every four digits from right to left are converted to decimal numbers, and the resulting data combination is the corresponding hexadecimal number. (Note: There are less than four high-order zeros). Example: (0101 1011)2=(5B)16 3: Octal conversion Binary: Each digit is converted to a three-digit binary digit Example: (13)8=(001 011)2=(1011)2 ( Note: Remove the first two 00, because 0 is not significant in the high position) 4: Hexadecimal conversion Binary: Each digit is converted to a four-bit binary number Example: (E3)16=(1110 0011)2

(b) integer constants

Integer constants come in three forms: decimal integer constants, octal integer constants, and hexadecimal integer constants.

(Note: There is no direct binary integer constant in the c language, and no binary will appear in the c language source.)

Write as follows:

Decimal integral constants: 123, 0, -24, 85L (long integer constants), etc. Octal integer constants: 051, -026, 0773, etc. Hexadecimal integer constants: 0x55, 0x1101, 0x, 0x5AC0, -0xFF. Where L is a long integer.

(c) Real constants

There are two types of real constants: decimal and exponential.

Decimal form: 5.4 0.074 -23.0 Index form: 5.4e0 4.3e-3 -3.3e4

(1) A real constant with a fractional part of 0 can be written as 453.0 or 453. (2) When expressed in decimal places, there must be numbers on both sides of the decimal point. Do not write ".453" and "453." and write "0.453" and "453.0." (3) When using exponential writing, there must be a number before e, and the index behind e must be an integer (Note: The integer order code can be a positive number, a negative number, or an octal number or a hexadecimal number, but it must be an integer. ).

(d) character constants

The sign of a character constant is a pair of single quotes ''. There are two types of character constants in the C language:

(1) A character enclosed by a pair of single quotation marks, such as 'a', 'r', '#'. Note: 'a' and 'A' are two different character constants.

(2) Enclosed by a pair of single quotation marks, preceded by a backslash \, followed by a number or letter, such as '', where "\" is the meaning of the escape, followed by a different character means a different meaning, such Character constants are escape characters. Specifically as shown.

Escaping characters Meaning of escaped characters ASCII code

Carriage return line-by-line 10 Horizontal jump to the next tab position 9 \b Backspace 8 Enter 13 \f Trailer Page 12 \\ Backslash "\" 92 \ 'Single quotes 39 \" Double quotes 34 \a Rings 7 \ddd Characters represented by 1 to 3 octal digits \xhh 1 Characters represented by ~2 hexadecimal digits

(5) String constants

In C language, a sequence of several characters enclosed in double quotes is a string constant.

Example: "ni hao" "happy" and so on.

(6) Symbolic Constants

The symbolic constant is a constant defined by the macro definition "#define", and the available identifier in the C program represents a constant.

Example: c program to calculate the area of ​​a circle.

#include #define PI 3.14159 main() { float r,s; r=12.5; S=PI *r*r; printf(“s= %f ”,s); }

Explanation:

#define is a macro definition. In this program, all occurrences of PI represent 3.14159, and PI is called a symbolic constant. Traditionally, we use uppercase letters to represent symbolic constants, and lowercase letters represent variables, which are easier to distinguish.

variable

A variable is an amount whose value can be changed. Variables have variable names that occupy a certain number of memory locations in memory. The value stored in the memory location is the value of the variable. Different types of variables have different memory locations, and variables must be defined before use.

(a) Integer variables

Integer variables fall into four categories: int, short int or short, long int or long, and unsigned int (unsigned short, unsigned long).

Different compilation systems have different rules for the number of digits and the range of values ​​occupied by the above four types of integer data.

Type specifier

Explanation:

The word signed indicates "signed" (that is, points with positive and negative numbers), not signing also implicitly signifies signing, and unsigned signifies "unsigned" (only positive).

(b) Real variables

In the C language, real variables are classified into single-precision types (float) and double types (double). Such as:

Float a , b ; double m ;

In vc, float data occupies 4 bytes (32 bits) in memory, and double data occupies 8 bytes. Single-precision real numbers provide 7 significant digits, and double-precision real numbers provide 15 to 16 significant digits. Real constants are not divided into float type and double type. A real constant can be assigned to a float or double variable, but the variable intercepts the corresponding valid number in the real constant according to its type.

Note: Real variables can only hold real values, real variables cannot be stored as integer variables, and integer values ​​cannot be stored as real variables.

(3) Character variables

Character variables used to store character constants, defined form:

Char variable name;

The keyword char defines the character data type, which occupies one byte of storage.

Example: char cr1,cr2; cr1= 'A', cr2='B';

When a character is assigned to a character variable, the character itself is not stored in memory but the ASCII code corresponding to the character is stored in the memory cell. For example, the character 'A' has an ASCII code of 65 and is stored in memory as follows:

Since the characters in the memory are stored in ASCII code, its storage form is similar to the storage form of integers. Therefore, character data and integer data in the C language can be commonly used. A character can be output in the form of characters, and integers can also be used. In the form of output, character data can also perform arithmetic operations, which is equivalent to the operation of their ASCII code.

Automatic conversion and cast of types

When the types of data in the same expression are different, the compiler automatically converts them to the same type and then performs calculations. The conversion priority is:

Char < int < float < double

That is, the type of "low" on the left side shifts to the right. Specifically, if the data with the highest priority in the expression is a double type, the other data in the expression is converted to a double type, and the calculation result is also a double type; if the data with the highest priority is in the expression Is a float type, then the other data in this expression is converted to a float type, and the calculation result is also a float type.

In the assignment operation, if the type of the left and right sides of the assignment number is different, the type of the right side of the assignment number is converted to the left type; when the type of the right side is higher than the type of the left side, the data of the right side is intercepted during the conversion.

In addition to automatic conversion, there is a mandatory conversion, the representation is:

(type) (expression); Example: (int)(a+b)

Discussion: When the value of a is assigned to 3.4 and the value of b is assigned to 2.7, what are the values ​​of (int)(a+b) and (int)a+b?

C operator recognition

The C language has a wide range of operators and can be divided into the following categories:

1, arithmetic operators: for all types of numerical operations. Including plus (+), minus (-), multiply (*), divide (/), seek surplus (%), increase (++), reduce (--) a total of seven kinds.

2, the assignment operator: used for assignment operations, divided into simple assignment (=), compound arithmetic assignment (+=,-=, *=, /=,%=) and compound bit operation assignment (&=,|=, ^=,>>=, <<=) There are 11 categories of three categories.

3, comma operator: used to combine several expressions into one expression (,).

4, the relationship operator: for comparison operations. Include more than (>), less than (<), equal (==), greater than or equal (>=), less than or equal to (<=), and not equal to (!=).

5, logical operators: for logic operations. Including (&&), or (||), non (!) three.

6, the conditional operator: This is a trinocular operator for conditional evaluation (?:).

7. Bit manipulation operator: The amount involved in the operation, which is calculated in binary bits. Including bit & (&), bit or (|), bit not (~), bit XOR (^), left shift (<<), right shift (>>) 6.

8, pointer operator: used to take content (*) and take the address (&) two kinds of operations.

9, find the number of operators: used to calculate the number of bytes occupied by the data type (sizeof).

10, special operators: brackets (), subscript [], members (→,.) And so on.

In addition, according to the number of objects involved in the operation, C language operators can be divided into: unary operators (such as!), binary operators (such as +,-) and trinocular operators (such as ?:).

Arithmetic operators and arithmetic expressions

First, the basic arithmetic operators

(1) + (Addition operator or positive operator, such as 2+5).

(2) - (subtraction operator or negative operator, such as 4-2).

(3) * (multiplication operator, such as 3*8).

(4)/(Division operator, such as 11/5).

The / operation is divided into two cases:

a. When both the left and right sides of the “Division” are integers, the result is necessarily an integer (Note: Only the integer part is used, not rounding)

For example: 5/2 is 2, not 2.5, and 1/2 is 0.

b. When at least one of the left and right sides of the “division” is real data (that is, decimal), the result is real data.

For example, the value of 5/2.0 is 2.5, and the value of 7.0/2.0 is 3.5.

(5)% (modulo operator or remainder operator, both sides should be integer data, such as 9% of the value of 7).

It should be noted that: When the operand is negative, the result varies from compiler to compiler. In vc, the sign of the result is the same as the dividend, for example: 13%-2 is 1, and -15% 2 is - 1.

Second, the priority and combination of arithmetic expressions and operators

An arithmetic expression is an expression that conforms to the C language syntax by concatenating operands (also called operands) with arithmetic operators and parentheses. Operands include functions, constants, and variables.

In computer languages, the law of evaluation of arithmetic expressions is similar to the law of four operations in mathematics, and its operating rules and requirements are as follows.

(1) In an arithmetic expression, multiple levels of parentheses can be used, but the parentheses must be paired. The operation begins with the inner parenthesis, and the values ​​of each expression are calculated from the inner to the outer.

(2) In arithmetic expressions, operators of different precedence can be operated from highest to lowest according to the operator's priority. If the operators in the expression have the same priority, they are combined according to the operator's direction. Operation.

(3) If the type of operands on either side of an operator is different, first use automatic conversion or forced type conversion so that the two have the same type, and then perform the operation.

Third, since the increase decrement operator

Effect: Increase or decrease the value of the variable by 1.

For example: ++i,--i (Before using i, first increase the value of i by 1 and decrease by 1). i++,i-- (after using i, increase the value of i by one and subtract one).

(1) Only variables can use the auto increment operator (++) and the decrement operator (--), and constants or expressions cannot be used, such as 10++ or (x+y)++ are illegal .

(2) The direction of the combination of ++ and -- is "from right to left," such as -i++. The left side of i is the negative operator. The right side is the auto increment operator. The negative and auto operations are self The right-to-left combination is equivalent to -(i++).

The auto-increment (decrease) operator is commonly used in loop statements. This operator is also used in pointers. Candidates should be clear about the "i++" and "++i" and "i--" and "--i" Differences, especially figure out the value of the expression and the value of the variable.

Assignment Operators and Assignment Expressions

First, the assignment operator and assignment expression

The assignment symbol "=" is an assignment operator. The role is to assign one data to one variable or assign the value of one variable to another. An expression consisting of an assignment operator is called an assignment expression. The general form is:

Variable name = expression

A variable can be assigned to a variable multiple times in the program. Each time the value is assigned, the data in the corresponding storage unit is updated once. The current data in the memory is the data that was last assigned.

Example: a=12; This expression reads "Assign the value of 10 to variable a".

Explanation:

a. If the operation object types on both sides of the assignment number are inconsistent, the system will automatically perform type conversion. The conversion rule: convert the type of the value of the right-side expression of the assignment number to the type of the left variable of the assignment number.

Example: int y=3.5; Finally, the integer 3 is stored in the variable y.

b. The value of the copy expression can be assigned to the variable again to form a continuous assignment.

For example: x=y=25 is a continuous assignment expression, and x=y=25 is equivalent to x=(y=25), so the expression x=y=25 has a final value of 25.

Second, the complex assignment operator

Adding other operators before the assignment operator constitutes a compound assignment operator. The compound operators related to arithmetic operations are: +=, -=, *=, /=, %=.

There can be no spaces between the two symbols. The precedence of the compound assignment operator is the same as that of the assignment operator. The expression n + 1 is equivalent to n = n + 1, the role is to take the value of the variable n increase by 1 and then assigned to the variable n, the operation rules of other compound assignment operators and so on.

For example, express the value of a+=a-=a*a, where the initial value of a is 12.

step:

(1) The "a-=a*a" operation is performed first, which corresponds to a=aa*a=12-144=-132. (2) Then perform the "a+=-132" operation, which is equivalent to a=a+(-132)=-132-132=-264.

Comma operator and comma expression

In C, the comma can be used as a delimiter, and it can also be used as an operator, the comma operator, to connect several expressions using the comma operator, for example, a=b+c,a=b* c, etc. are called comma expressions.

The general form is:

Expression 1, Expression 2, Expression 3, ..., Expression n

Example: x=2, y=3, z=4

The comma expression has the associativeness from left to right, that is to solve the expression 1 first, then solve the expression 2 sequentially, until the value of the expression n. The value of the expression n is the value of the entire comma expression. The value of the above comma expression is the value of the expression z=4. It should be noted that the comma operator is the lowest of all operators.

Example: There are the following program segments:

Main() { int a=2,b=4,c=6,x,y; y=(x=a+b),(b+c); printf("y=%d,x =%d",y,x); }

The program shows the result: y=6, x=6

Discuss: Change the result of y=(x=a+b),(b+c); to y=((x=a+b),b+c)?

Relational operators and relational expressions

First, the logic in the C language

There are only two logical values ​​in the C language: true and false. Use non-zero for true, zero for false. Therefore, for any expression, if its value is zero, it represents a false value. If its value is non-zero, it represents a true value. As long as the value is not zero, either a positive number, a negative number, an integer, or a real number represents a true value. For example, the logical value of -5 is true.

Second, the logical expression

"&&" and "||" have two operands, so they are both binocular operators, and! The operation object is only one, so it is a unary operator. Examples of logical operations are as follows:

(1)a&&b: When both && are true, the values ​​of the expression a&&b are true.

It is worth noting that in mathematics, relational 0

(2)a||b: When both sides of || are true, the value of the expression a||b is true.

(3)!a: means to negate, if a is true, then !A is false, and vice versa. E.g! The value of -5 is 0.

In C language, a logical expression consisting of && or || will produce a "short-circuit" phenomenon under certain circumstances.

(1)x && y && z , only when x is true (non-zero), we need to determine the value of y; only when x and y are true, we need to determine the value of z; as long as x is false, we don't have to To distinguish y and z, the value of the entire expression is 0. Word of mouth: "A false must be false."

Example: (!5==1)&&(++i==0) (!5==1) The value of the expression is 0, so the computer skips (++i==0) this expression. ,(!5==1)&&(++i==0) The value of the expression is 0.

(2)x||y||z, as long as the value of x is true (non-zero), it is not necessary to discriminate the values ​​of y and z, the value of the entire expression is 1, only the value of x is false, only need to determine y The value of only the value of x and y is false at the same time need to determine the value of z, saying: "A true must be true."

Bit operation

A bit operator

In computers, data is stored in the form of binary numbers. Bit operations refer to operations on binary bits in memory locations. The C language provides 6 bit operators.

Second, bit operation

Bit Operators & |~<< >> ∧ The order in descending order of priority is:

The bit operator's inversion operation "~" has the highest priority, while the left shift and the right shift are the same as the second, and the next order is bitwise with "&", bitwise exclusive OR "∧" and bitwise or " ". The order is ~ << >> & ∧ |.

Example 1: The left shift operator "<<" is a binary operator. Its function shifts all the binary digits of the operand on the left of “<<” to the left. The number of digits shifted by the number on the right of “<<” specifies the number of digits to be shifted. The high digit is discarded, and the low digit is 0.

For example: a<<4 refers to moving each binary digit of a to the left by 4 digits. For example, if a=00000011 (decimal 3), the left shift is 00110000 (decimal 48).

Example 2: The right shift operator ">>" is a binary operator. Its function is to shift all binary digits of the operand on the left of ">>" to the right by a number of digits, and the digits on the right of ">>" specify the number of digits to move.

For example: Let a=15, a>>2 to right shift 000001111 to 00000011 (decimal 3).

It should be noted that for signed numbers, the sign bit will move with the right shift. When it is a positive number, the highest bit is filled with 0. When it is negative, the sign bit is 1, and the most significant bit is a zero or a complement one, depending on the rules of the compilation system.

Example 3: Let the binary number a be 00101101. If the high 4 bits of a are negated by the XOR operation a∧b, and the low 4 bits are unchanged, then the binary number b is.

Analysis: XOR operation is often used to reverse a specific bit, as long as the bit to be flipped is XORed with 1 because the bit whose value is 1 in the original is XORed with 1 to get 0, the median of the original value. An exclusive OR of the bits 0 and 1 results in 1 . The bits that are XORed with 0 will remain as they are. XOR operations can also be used to exchange two values ​​without using temporary variables.

Such as int a = 3, b = 4;, would like to exchange the value of a and b, can be achieved by the following statement: a = a ∧ b;

b=b∧a;

a=a∧b;

So the answer to this question is: 11110000.

C language is a very suitable language for programming entry, and the importance of laying a solid foundation is self-evident. Therefore, old Jiujun hereby offers this piece of dry goods, hoping that young partners can benefit from it.

Energy Storage System

Integrated Energy solution with solar power, wind power, battery energy storage system, and diesel and gas generators. application for mobile power porter, household ESS sysytem with battery energy and solar PV unit. peak load for induatial and grid application.

solar power, battery, battery energy storage, CATL, PV Unit, Li(NiCoMn)O2 Battery, LiFePO4 Battery

Guangdong Superwatt Power Equipment Co., Ltd , https://www.swtgenset.com