C Language Basic Knowledge collation

Source: Internet
Author: User

With a simple example of C program, the basic composition, format and good writing style of C language basic knowledge are introduced, so that the small partners have a preliminary understanding of C language.

Example 1: A C program that calculates the sum of two integers:

#include
Main ()
{
int a,b,sum;
a=20;
b=15;
Sum=a+b;
printf ("a=%d,b=%d,sum=%d\n", a,b,sum);

}
Key notes:

1. any C language program must include the following format:

Main ()
{   }

This is the basic knowledge structure of C language, and any program must contain this structure. If nothing is written in parentheses, the program will not perform any results.

2,main ()----called the "main function" in the C language, a C program has and only one main function, any C program always starts from the main function, a pair of parentheses after the main function can not be omitted.

3 . The content enclosed in braces {} is called the function body of the main function, which is what the computer is going to do.

4 . In {} There is a semicolon (;) in the back of each sentence, in C, we call a sentence with a semicolon ending as a C language, and a semicolon is a sign of the end of the statement.

5,printf ("a=%d,b=%d,sum=%d\n", a,b,sum); ----through the implementation of this C language system provided to us directly using the screen output function, the user can see the results of the operation, the program will be run, the following results are displayed on the display:

a=20,b=15,sum=35

6.#include

Note: (1) starting with the # (2) not ending with a semicolon
This line does not have a semicolon, so it is not a statement, which is called a command line in C, or "Precompiled Processing command".

7, the program in the end of the part of the program's comment section, note can be added anywhere in the program, in order to improve the readability of the program is added, but the computer performs the main function of the contents of the comment is completely ignored, in other words, the computer as the annotation part does not exist in the main function.

C Program Generation Process

C programs are generated by the source files compiled by the target file, and then connected to build the executable file.

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

Identifier

When writing a program, you must name the function, variable, and so on, which is called an identifier. The naming rules for identifiers in C are as follows:

    • Identifiers can only consist of letters, numbers, underscores;
    • The first letter of an identifier must be a letter and an underscore;
    • Identifiers distinguish between uppercase and lowercase letters, such as if and if are two completely different identifiers.

The
legal identifiers are as follows:
A6, B_3, _mn
The illegal identifiers are as follows:
Ab#12, 8m, tr3:4, yes no

Identifiers cannot be the same as keywords that have special meanings in the program, cannot be the same as user-compiled function names, C language library functions, and the various identifiers in the program should not be duplicated so as to differentiate. When choosing a variable name and other identifiers, you should be careful to "see the name and know the meaning."

Identifiers fall into the following three categories:

1. Key words

A keyword is a class of identifiers that have a specific meaning that is specifically used to describe a specific component of C, and 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 identifiers


Predefined identifiers also have specific meanings in the C language, but can be used as user identifiers, and predefined identifiers fall into two categories:

(1), library function name, for example (Printf,scanf,sin,isdigit, etc.)
(2), compile and process the command name, for example (Define,include)

3. User identifier

The user is called the user identifier according to the identifier that he or she defines. Regardless of the custom identifier, you must conform to the three naming rules of the identifier.

Constant

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

(i) Numeric conversions

Four forms of representation of numbers:

①: binary: All numbers are composed of 0, 1, every binary one, binary number does not appear 2.
Example: 110101
②: octal: With the number 0 (note does not start with the letter o,o), all numbers are composed of 0~7, every eight in one, octal number does not appear 8.
Example: 0112,0123,077, etc.
③: decimal: All numbers are made up of 0~9, every ten in one, the decimal number does not appear 10.
Example: 0,12,-15, etc.
④: 16 binary: Starting with 0x or 0X (number 0 plus letter x), all numbers are made up of 0~9,a~f (or a~f), 16 in one (where a, B, C, D, E, F respectively represent 10, 11, 12, 13, 14, 15)
Example: 0x4A, 0X14C7, etc.

Inside the computer, the numbers are represented in binary form and stored, the user input of the ordinary decimal digits to be converted into binary computer to the computer to store, the same computer operation results are also binary, generally to convert it to a decimal number and then output to the user to read, this conversion is usually automatically implemented by the computer.

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

Division: divides the decimal number by 2, records the remainder, the resulting quotient continues to divide by 2, until the quotient is 0, and then the remainder of each get together from the backward forward order, the resulting remainder number sequence is the decimal number corresponding to the binary number. The octal and 16 binary conversion methods are the same as above.

Example: The decimal number 13 is converted to a binary number with a value of 1101, the conversion octal is 015, and the conversion to the 16 binary is d.

(2) converting binary, octal, and 16 into decimal

Sum of products: multiply each of the binary from low to high (the right is low, the left is high) multiplied by 20,21,22 .... , and then sum the product.

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

(3) conversion between binary and octal, hexadecimal numbers

①: Binary to octal: from right to left each three-bit group converted to decimal number, the resulting data combination is the corresponding octal number (note: High-level less than three-bit 0).
Example: (010 110 111) 2 = (267) 8
②: Binary turn 16 binary: From right to left every four bits of a group converted to decimal number, the resulting data combination is the corresponding hexadecimal number (note: High-level less than four bit 0).
Example: (0101 1011) 2= (5B) 16
③: Octal conversion binary: Converts each digit to a three-bit binary number
Example: (13) 8 = (001 011) 2 = (1011) 2
(Note: Remove the previous two 00, because 0 is meaningless at high level)
④: Hexadecimal conversion binary: converts each digit to a four-bit binary number
Example: (E3) 16= (1110 0011) 2

(ii) Integral type constants

There are 3 types of integer constants: decimal integer constants, octal integer constants, and hexadecimal integer constants.

(Note: There is no integer constant in the C language that directly represents the binary, and no binary is present in the C-language source program.) )

Here's how to write:

decimal Integer constant: 123, 0, -24, 85L (Long integer constant), etc.
Octal integer constants: 051,-026, 0773, etc.
Hexadecimal integer constants: 0x55, 0x1101, 0x, 0x5ac0, -0xff.
Where L is a long integer type.

(c) The real type constant

There are two representations of real constants: decimal form and exponential form.

decimal form: 5.4 0.074-23.0
Exponential form: 5.4e0 4.3e-3 -3.3e4
(1) The number of decimal parts is divided into 0 real constants, can be written as 453.0 or 453.
(2) In decimal notation, the two sides of the decimal point must have a number, cannot be written as ". 453" and "453." and should be written as "0.453" and "453.0".
(3) When using exponential notation, there must be a number before e, and an exponent after E must be an integer (note: The integer order can be positive, negative, octal, hexadecimal, but must be an integer).

(iv) Character constants

The character constants are marked by a pair of single quotes ', and there are two types of character constants in the C language:

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

(2) by a pair of single quotation marks, with a backslash \ Start, followed by several numbers or letters, such as ' \ n ', where "\" is the meaning of escaping, followed by different characters to indicate a different meaning, such a character constant is called an escape character. Specific.

the meaning of escape character escapes ASCII code
\ nthe carriage return to newline 10
\ t jumps horizontally to the next tab position 9
\b Backspace 8
\ r Enter 13
\f Go paper Page 12
\ \ backslash character "\" 92
\ ' Single-quote character 39
\ "Double-quote character 34
\a Bells 7
\DDD the characters represented by the number of octal digits
\xhh the characters represented by hexadecimal digits

(v) String constants

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

Example: "Ni Hao" "Happy" and so on.

(vi) Symbolic constants

Symbolic constants are constants defined by the macro definition "#define", which represent a constant in a C program.

Example: A C program that calculates 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);
}

Description:#define is a macro definition, where all pi occurrences in this program represent 3.14159, while Pi is called a symbolic constant. It is customary to use uppercase letters to denote symbolic constants, and lowercase letters to represent variables, which makes it easier to differentiate.

Variable

A variable is a quantity whose value can be changed. Variables have variable names, which occupy a certain storage unit in memory, and the value of the variable is stored in the storage unit. Variables of different types have different sizes of storage units, and variables must be defined before they are used.

(i) Integer variables

There are 4 types of integer variables: basic type (int), short integer (shorter int or shortly), long integer (long int or long), and unsigned (unsigned int, unsigned short,unsigned long).

Different compiling systems have different rules for the number of bits and ranges used in the four types of integer data.

Type descriptor

Description

The
word signed to indicate "signed" (that is, there are positive negative numbers), do not write signed is also implied as signed, unsigned is used to describe "unsigned" (only positive numbers).

(b) Real variables

In C, real variables are divided into single-precision type (float) and double-precision type (double). Such as:

float A, b;
Double m;

In VC, the float type data occupies 4 bytes (32 bits) in memory, and the double type data occupies 8 bytes. Single-precision real numbers provide 7-bit valid digits, and double-precision real numbers provide 15~16 digits. Real constants are non-float and double, and a real constant can be assigned to a float or double type variable, but the variable intercepts the corresponding valid number in the real constant based on its type.

Note: Real variables can only hold real values, cannot use integer variables to hold real values, and cannot hold integer values with real variables.

(c) Character variables

Character variables are used to store character constants and define the form:

char variable name;

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

Example: Char cr1,cr2;
Cr1= ' A ', cr2= ' B ';

When a word is assigned to a character variable, instead of storing the character itself in memory, the ASCII code corresponding to that character is stored in the memory unit. For example, the ASCII code for character ′a′ is 65, and the memory is stored in the following form: 01000001

Since in-memory characters are stored in ASCII code, the storage form is similar to that of integers, so the character data and integer data in C can be generalized, a character can be output in the form of a character, output in an integer, and character data can also be performed in arithmetic operations. This is equivalent to the operation of their ASCII code.

Types of auto-conversions and casts

When the types of data in the same expression are different, the compiler automatically converts them to the same type before they are evaluated. The conversion priority level is:

Char < int < float < double

That is, the left-level "low" type is converted to the right. Specifically, if the highest priority data in an expression is a double type, the other data in this expression is converted to double type, and the result is double type; if the highest priority data in an expression is float type, The other data in this expression is converted to float type, and the result is a float type.

In the assignment operation, the right-hand type of the assignment number is converted to the left type, and the right-hand data is intercepted when the right-hand type is higher than the left-side type.

In addition to automatic conversions, there are casts, which are represented as:

(type) (expression);
Example: (int) (A+B)

discussion: What is the value of a value assigned to an 3.4,B value of 2.7, (int) (A+B) and (int) a+b, respectively?

C Operator Awareness

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

1, arithmetic operators: For all kinds of numerical operations. Including plus (+), minus (-), multiply (*), except (/), balance (%), self-increment (+ +), self-reduction (--) a total of seven.

2, assignment operator: For assignment operation, divided into simple assignment (=), compound arithmetic Assignment (+=,-=,*=,/=,%=) and compound bit operation Assignment (&=,|=,^=,>>=,<<=) Three class total 11 kinds.

3, comma operator: Used to combine several expressions into an expression (,).

4 . Relational operators: Used for comparison operations. Includes more than (>), less than (<), equals (= =), greater than or equal (>=), less than or equal (<=), and not equal to (! =) Six.

5, logical operators: for logical operations. Included with (&&), or (| |), non-(!) Three kinds.

6 . Conditional operator: This is a three-mesh operator for conditional evaluation (?:).

7, bitwise operators: Participate in the amount of the operation, according to BITS operation. There are six kinds of bits and (&), bit or (|), bit non (~), bit xor (^), left (<<), right Shift (>>).

8, pointer operator: for the content (*) and Fetch address (&) Two kinds of operations.

9, the number of bytes operator: the number of bytes (sizeof) used to calculate the data type.

10 . Special operators: Parentheses (), subscript [], member (→,.) and several others.

In addition, the C-language operator can be divided into: monocular operator (such as!) by the number of objects participating in the operation.  ), binocular operators (such as +,-), and three-mesh operators (such as : )。

Arithmetic operators and arithmetic expressions

First, the basic arithmetic operator

(1) + (addition 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 situations:

A, "except" Both sides of the left and right are integers, the result is necessarily an integer (note: Take only the integer part, not rounding)

For
Example: A value of 5/2 is 2, not a value of 2.5,1/2 is 0.
B, "except" the left and right sides of at least one is the real data (that is, decimal), the result is the real data.

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

(5)% (modulo operator or call remainder operator,% of both sides shall be integral type data, such as the value of 9%7 2).

It is necessary to note that when the operand is negative, the result is different from the compiler, in the VC, the sign of the result is the same as the divisor, for example: 13%-2 value is 1, and -15%2 value is-1.

Precedence and binding of arithmetic expressions and operators

An arithmetic expression is an expression that conforms to the C syntax rules by using arithmetic operators and parentheses to concatenate operands (also called operands). Operands include functions, constants, variables, and so on.

In computer language, the arithmetic expression is similar to the law of arithmetic in mathematics, and its operation rules and requirements are as follows.

(1) In an arithmetic expression, you can use a multilayer parenthesis, but the parentheses must be paired. The value of each expression is computed from the inside of the parentheses, starting at the inner parenthesis.

(2) in arithmetic expressions, for operators of different precedence, operations are performed by the precedence of the operator from high to low, and if the operators in the expression have the same precedence, the operator is combined in the same direction.

(3) If the operand types on either side of an operator are different, then the automatic or coercion type conversion is used to make the two have the same type and then perform the operation.

Three, self-increment self-decrement operator

Effect: Increases the value of the variable by 1 or minus 1.

such as: ++i,--i (before using I, the first value of I plus 1, minus 1).
i++,i--(after using I, the value of I is added 1, minus 1).

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

(2) + + and--the binding direction is "from right to left", such as-i++, I left is the minus operator, the right is the increment operator, minus and self-increment operations are "from right to left", equivalent to-(i++).

In circular statements commonly used in the self-increment (minus) operator, in the pointer is also commonly used to the operator, candidates to understand the "i++" and "++i" and "i--" and "I" differences, especially to clarify the value of the expression and the value of the variable.

Assignment operators and Assignment expressions

An assignment operator and an assignment expression

An assignment symbol "=" is an assignment operator that assigns a data to a variable or assigns the value of a variable to another variable, and an expression consisting of an assignment operator is called an assignment expression. The general form is:

Variable name = Expression

In the program can be assigned to a variable multiple times, each time the value, and its corresponding storage unit data is updated once, the current data in memory is the last time the value of the data.

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

Note:A, if the assignment number on both sides of the operand type is inconsistent, the system will automatically type conversion, the rule of conversion: the assignment number to the right of the expression of the type of the value of the argument to the left of the type of the variable,

example: int y=3.5; The integer 3 is finally stored in the variable y.

b, the value of the copy expression can be assigned to the variable, forming a continuous assignment.

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

Two, compound assignment operator

The addition of other operators before the assignment operator can form a compound assignment operator. Where the compound operators related to arithmetic operations are: +=,-=,*=,/=,%=.

There can be no spaces between two symbols, and the precedence of a compound assignment operator is the same as the assignment operator. The expression N+=1 is equivalent to n=n+1, the function is to take the value of the variable N 1 and then assign to the variable n, the other compound assignment operator of the operation rules and so on.

If the value of the expression A+=a-=a*a, where a is the initial values of 12.

Steps:

(1) The first "a-=a*a" operation, the equivalent of a=a-a*a=12-144=-132.
(2) then the "a+=-132" operation, equivalent to a=a+ (-132) =-132-132=-264.

Comma operators and comma expressions

In C, commas, in addition to being delimiters, can also be used as an operator----a comma operator to concatenate several expressions with a comma operator, such as a=b+c,a=b*c, such as a comma expression.

The general form is:

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

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

The comma expression has a left-to-right binding, which is to solve the expression 1 first, then solve the expression 2 in turn until the value of the expression N. The value of an expression n is the value of the entire comma expression. The value of the comma expression above is the value of the expression z=4 4. It should be noted that the comma operator is the lowest level in all operators.

Example: There are the following program sections:

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 displays the result as: y=6,x=6

Discussion: Will y= (X=a+b), (b+c), be changed to y= ((x=a+b), b+c) program results?

Relational operators and relational expressions

Logical values in the first and C languages

There are only two logical values in the C language: True (True) and False (Flase). The non-0 represents true, and 0 represents a false. Therefore, for any one expression, if its value is zero, it represents a false value, if its value is nonzero, it represents a truth. As long as the value is not 0, either positive, negative, integer, or real, all represent a truth. For example, the logical value of 5 is true.

Ii. Logical Expressions

"&&" and "| |" There are two operands, so they are both binocular operators, and! Has only one operand, so it is the monocular operator. Examples of logical operations are:

(1) A&&b: The value of the expression A&&b is true when both sides of the && are true.

It is worth noting that: in mathematics, the relational formula 0

(2) a| | B: When | | When there is a "true" on both sides, the expression a| | The value of B is true.

(3)!a: To take the reverse, if a is true, then! A is false and vice versa. For example! -The value of 5 is 0.

In the C language, by && or | | A logical expression consisting of, in some specific cases, a "short-circuit" phenomenon.

(1) x && y && z, only if X is true (not 0), the value of Y needs to be judged, and only X and Y are true, so the value of z must be determined, so long as X is false it is not necessary to discriminate Y and Z, and the value of the entire expression is 0. Formula: "A false will be false."

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

(2) x| | y| | Z, as long as the value of X is True (not 0), you do not have to distinguish the values of Y and Z, the value of the entire expression is 1, only the value of the x is false, you need to determine the value of Y, only the values of x and Y are false in order to determine the value of Z, the formula: "A true

Bit arithmetic

One, bitwise operators

In the computer, the data are stored in binary number form, bit operation refers to the operation of bits in the storage unit. The C language provides 6 bit operators.

Second, bitwise operations

The order of bitwise operators & |~<< >>∧ by priority from highest to lowest is:

In the bitwise operator, the negation operation "~" has the highest precedence, while the left and right shifts are the same, and the next order is bitwise AND "&", Bitwise XOR or "∧", and bitwise OR "|".  Order for ~ << >> &∧| 。

Example 1: The left shift operator "<<" is the binocular operator. Its function to the left of the "<<" operand of all the binary all left a number of bits, the "<<" to the right of the number to specify the number of bits moved, high drop, low 0.

For example:
A<<4
Moves the binary of a to the left by 4 bits. such as a=00000011 (decimal 3), 00110000 (decimal 48) After moving left 4 bits.

Example 2: Right-shift operator ">>" is the binocular operator. The function is to shift all the binary of the left operand of ">>" to the right of several bits, and the number to the right of ">>" to specify the number of bits to move.

For example:
Set A=15,
A>>2
Indicates that 000001111 is shifted to the right of 00000011 (decimal 3).

It should be stated that, for the signed number, when moving right, the symbol bit is moved along with it. When positive, the highest bit is 0, while negative, the sign bit is 1, the highest bit is 0 or the complement 1 depends on the requirements of the compilation system.

Example 3: Set the binary number A is 00101101, if through the XOR Operation A∧b the high 4 bit of a is reversed, the lower 4 bits unchanged, then the binary number B is.

Resolution: The XOR operation is often used to make a particular bit flip, as long as the need to flip the bit with 1 XOR or operation can be, because the value of the original number of 1 and 1 is different or operation 0, the original number of the value of 0 is different or operation Results 1. The bits that are XOR with 0 will remain the original value. An XOR operation can also be used to exchange two values without a temporary variable.

such as int a=3, b=4;, want to swap the value of a with B, use the following statement to implement:
A=a∧b;

B=b∧a;

A=a∧b;

So the answer to this question is: 11110000.

C language as a very suitable for the introduction of programming language, the importance of playing the basic knowledge of C language is self-evident. So the seniors are here to take this piece of dry goods, hope that the small partners can benefit from it.

C Language Basic Knowledge collation

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.