C Language 01 in-depth understanding of basic concepts (1)

Source: Internet
Author: User
Tags define definition

C Language 01 in-depth understanding of basic concepts (1)
Basic Data Type Analysis Data Type
What is a data type?
? The data type can be interpreted as an alias with a fixed memory size.
? The data type is the model for creating variables.

Nature of Types
Char
Short
Int
1 byte
2 byte
4 byte
Memory space
Char c
Short s
Int I

Variable nature
? A variable is an alias for an actual Continuous Bucket.
? Apply for and name a bucket using variables in the program
? You can use a bucket by using the variable name.
Auto, register, static analysis auto
? Variables in C can have their own attributes.
? You can add the "attribute" keyword when defining a variable.
? The "attribute" keyword specifies the unique meaning of a variable.
? Auto is the default attribute of local variables in C language.
? By default, all local variables of the compiler are auto.

? The static keyword specifies the "static" attribute of the variable.
? Static has the meaning of "Scope qualifier" at the same time.
? Static modified local variables are stored in the static area of the program.
? Another significance of static is the File Scope identifier.
-The scope of the global variable modified by static is only in the declared file.
-The static modified function scope is only in the declared file.

Register
? The register keyword indicates that the variable is stored in the register.
? Register only requests register variables, but not necessarily the request is successful.
? The register variable must be a value acceptable to the CPU register.
? You cannot use the & operator to obtain the address of the register variable.

? Summary
? Auto variables are stored in the stack of the program. Default attributes
? Static variables are stored in the static area of the program.
? The register variable request is stored in the CPU register

If, switch, do, while, for analysis
Analysis of branch statements -- if
? If statements are used to select execution statements based on conditions.
? Else cannot exist independently and always matches the nearest if
? Other if statements can be connected after the else statement

? Notes for comparing null values in if Statements
? Bool variables should appear directly in the condition and should not be compared.
? When a common variable is compared with a value 0, the value 0 should appear on the left of the comparison symbol.
? Float variables cannot be compared with 0 values directly, so precision must be defined.

Analysis of branch statements -- switch
? The switch statement corresponds to multiple values of a single condition.
? Each case statement branch must have a break. Otherwise, the Branch will overlap.
? The default statement must be added to handle special cases.
Expression
Default Statement 1 1 Statement 2 2 Statement 3 3
Break

? The Value in the case statement can only be of the integer or case type.
? Case statement arrangement Sequence Analysis
? Sort statements in alphabetical order
? The normal situation is put at the beginning, and the exception is put at the end
? The default statement is only used to handle real default conditions.

Branch Statement Analysis
? Summary
? The if statement is used in the case where "slice" is required for determination.
? The switch statement is used to determine discrete values separately.
Disconnected
? The if statement can safely Replace the switch statement in the function,
Switch statement cannot replace if statement
? The switch statement is more concise for multi-branch judgment

Loop Statement Analysis
? Basic Method of loop statements
? Determine whether to execute the loop body using a conditional expression
? The conditional expression follows the if statement expression principle.


? Do, while,
? The do statement is executed first and then determined. The loop body must be executed at least once.
? The while statement is judged first and then executed. The loop body may not be executed.
? The for statement is judged first and then executed, which is more concise than the while statement.

? Difference between break and continue
? Break indicates terminate the execution of the loop
? Continue indicates that the current loop body is terminated and the next loop is executed.

Note: The swicth statement cannot be used together with the continue statement.

Goto, void, extern, sizeof Analysis

Abandoned goto
? Sub-rule: Disable goto
? Project Experience: The program quality is inversely proportional to the number of goto appearances
? Final decision: Move goto to the Cold palace

Significance of void
? Void modifier function return value and Parameters
? If the function does not return a value, declare it as void.
? If the function has no parameters, you should declare the parameter as void.
Void modifier function return value and parameter only to indicate none

The void variable does not exist.

The C language does not define how much memory the void is.

No void ruler

Unable to crop the variable corresponding to void in memory

? Significance of void pointer
? The C language requires that only pointers of the same type can be assigned values to each other.


? Void * the pointer is used as the left value to receive any type of pointer.


? Void * forced type conversion is required when the pointer is assigned to another pointer as the right value


Meanings hidden in extern
? Extern is used to declare variables and Functions Defined externally.
? Extern is used to "tell" the compiler to compile in C mode
The C ++ compiler and some variant C compilers will compile in the "self" mode by default.
Functions and variables, through the extern key can command the compiler "to the Standard C side
".

Is named sizeof
? Sizeof is the built-in indicator of the compiler, not a function.
? Sizeof is used to calculate the memory size occupied by the corresponding entity
? The value of sizeof has been determined during the compilation period.

Const and volatile analyze const modifier Variables
? In C language, the variable modified by const is read-only, and its essence is variable.
? The const variable occupies space in the memory.
? Essentially, const is only useful to compilers and useless during runtime
The original const is not a real constant.

Const modifier Array
? In C, the const modified array is read-only.
? The array space modified by const cannot be changed.

Const modifier pointer (determine whether const modifies p or * p)
? Const int * p; // p variable. The content pointed to by p cannot be changed.
? Int const * p; // p variable. The content pointed to by p cannot be changed.
? Int * const p; // p is unchangeable, And the content pointed to by p is variable.
? Const int * const p; // The content pointed to by p and p cannot be changed.
Tip: left and right fingers
When const appears on the left side of *, the data pointed to by the pointer is a constant.
When const appears on the right side of *, the pointer itself is a constant.

Const modifier function parameters and return values
? The const modifier function parameter indicates that you do not want to change the parameter value in the function body.

 

? The Return Value of the const modifier function indicates that the return value cannot be changed and is mostly used to return pointers.


Volatile
? Volatile can be understood as "compiler warning indicator"
? Volatile is used to tell the compiler that the variable value must be retrieved from the memory each time.
? Volatile mainly modifies variables that may be accessed by multiple threads.
? Volatile can also modify variables that may be changed by unknown factors.

Struct and union Analysis

Flexible array generated by struct
? Flexible array: an array of undetermined size
? The last element of the struct in C can be an array of unknown sizes.
? A flexible array can be generated by struct in C.

Difference between union and struct
? Each field in struct is allocated independently in the memory.
? Union only allocates space for the largest domain. All domains share the space.
Notes for using union
? The use of union is affected by the system size.

Enum and typedef Analysis

How to Use enumeration types
? Enum is a custom type.
? The default enum constant is incremented by 1 based on the previous value.
? Enum type variables can only take discrete values when defined

Enumeration type and # define
? # Define macro constants are simply replaced by values, which are often enumerated.
Volume is a constant in the true sense.
? # The define macro constant cannot be debugged, And the enumerated constant can
? # Define macro constants have no type information. Enumeration constants are special
Constant of the specified type

Interview ......
Examiner: Can you tell me the specific meaning of typedef?
Applicant: typedef is used to define a new type...
? Typedef is used to rename an existing data type.
? Typedef does not generate a new type
? Type defined by typedef cannot be unsigned or signed extended.

Difference between typedef and # define
? Typedef is an alias for an existing type.
? # Define is a simple string replacement with no alias

Annotator

Annotator
? Comment Rule Summary
? The compiler will delete comments during the compilation process, but will not simply delete the comments, but use null
Lattice substitution
? The compiler considers that the content enclosed in double quotes is a string, and the double slash is no exception.
? "/*…… */"-Type annotations cannot be nested

Annotator
? What do you think Y = x/* p means? ?
Author's intention: Divide x by * p and assign the result to y
Compiler: Use/* as the beginning of a comment, and
The content is treated as the comment until */appears.
In the compiler's view, annotations are equal to other program elements. Therefore,
As a programmer, you cannot look down on comments.

? You can write excellent comments.
? Annotations should be accurate and easy to understand to prevent ambiguity. Incorrect annotations are harmful and not profitable.
? Annotations are code prompts to avoid being bloated and overwhelming
? Clear code to avoid comments
? Do not use abbreviations to comment out the code, which may cause misunderstanding.
? Annotations are used to explain the reason rather than to describe the running process of the program.

Connection and escape characters

? The concatenation operator (\) in C is a powerful tool to indicate compiler behavior.

? Use of the connection string:
? The compiler removes the backslash, and the characters following the backslash are automatically removed before
One row
? When a word is followed, no space is allowed after the backslash, And the next line of the backslash is
There cannot be spaces before
? The concatenation operator is suitable for defining macro code blocks.

? The Escape Character (\) in C is mainly used to indicate that no echo character is displayed.
Used to indicate regular characters

Summary
? The backslash (\) in the C language simultaneously serves as a connection character and an escape character.
? When the backslash is used as a connection character, it can appear directly in the program.
? When a backslash is used as an escape character, it must appear in a character or string.

Single quotes and double quotes? Single quotes in C are used to represent character constants.
? Double quotation marks in C are used to represent string constants.
'A' indicates a character constant.
1 byte in memory
'A' + 1 indicates the 'A' ASCII code plus 1, and the result is 'B'
"A" indicates a String constant.
2 bytes in memory
"A" + 1 indicates pointer operation, and the result points to the "a" Terminator '\ 0'

Single quotation marks and double quotation marks
? Summary
? A character enclosed in single quotes represents an integer.
? A character enclosed in double quotation marks represents a pointer.
? The C compiler accepts the comparison between characters and strings, which is meaningless.
? The C compiler allows a string to assign values to character variables, which is ridiculous.
Analysis of logical operators? Logical operators &, | and! Is it really simple?

Short-circuit rule:
? | The calculation starts from left to right. If the condition is true
When the calculation is stopped, the entire expression is true; all conditions
If it is false, the expression is false.
? & Start from left to right when a false entry is encountered
When computing is stopped, the entire expression is false; all
Is true.

? "!" What is it?

The logical character "!" in C Only recognize 0, only know that 0 will return 1.
Therefore, when the value is not 0, the result is 0.

? The three-object operator (? B: c) can be used as the carrier of logical operators
? Rule: if the value of a is true, the value of B is returned; otherwise, the value of c is returned.
Bitwise operator analysis? Bitwise operators in C Language
Shift right>
Shift left <
Reverse retrieval ~
By bit or ^
By bit or |
Bitwise AND &

? Shift left and shift right notes
? Left shift operator <shifts the binary bit of the number to the left
? Rule: discard at a high level and add 0 at a low level.
? Right Shift Operator> shifts the binary number to the right
? Rule: high sign bit complement, low discard
Pay attention to the value of complement bits!


? Error Prevention rules:
? Avoid bitwise operators. logical operators and mathematical operators appear in one expression at the same time.
Medium
? When bitwise operators, logical operators, and mathematical operators need to be involved in the operation at the same time
Brackets () are used to express the computing order.
TIPS:
? Shifting n places left is equivalent to multiplying n to the power of 2, but the efficiency is higher than that of mathematical operators.
? Shifting n places to the right is equivalent to dividing by the n power of 2, but the efficiency is higher than that of mathematical operators.
++, -- Operator Usage Analysis
? A pair of headaches
What do you think is the value of this expression?

? In the test interview, ++ I
A ++ B
A ++ B
A ++ B

? Method greedy method--- ++, -- expression reading skills
? Each symbol processed by the compiler should contain as many characters as possible.
? The compiler reads as many characters as possible from left to right.
? Analysis on conversion of priority and type when the characters to be read cannot form valid characters with the characters to be read

? Implicit type conversion in C Language
? In arithmetic formula, the low type is converted to the high type.
? In the value assignment expression, the expression value is converted to the type of the variable on the left.
? When a function is called, the real parameter is converted to the type of the form parameter.
? Function return value. The return expression is converted to the return value type.
Int-> unsigned int-> long-> unsigned long-> double
Float
Char
Short

Macro definition and Usage Analysis? # Define definition macro constants can appear anywhere in the code
? # Define can use this macro constant for subsequent code starting from this line

? # Define expressions give function call illusion, but not function
? # Define expressions can be more powerful than Functions
? # Define expressions are more error-prone than Functions

? Macro expressions are processed during pre-compilation. The Compiler does not know macro expressions.
Exist
? Macro expressions use "real parameters" to completely replace the form parameters without any operation.
? Macro expressions do not have any "call" overhead
? Can recursive definition conditions not appear in macro expressions for compilation and analysis? Conditional compilation is similar to if… in C... Else
? Conditional compilation is a pre-compilation command used to control whether to compile a code segment.

? # The essence of include is to embed existing file content into the current file.
? # Include indirectly contains actions that will also generate embedded file content

Significance of Conditional compilation
? Conditional compilation allows us to compile different code segments based on different conditions,
Therefore, different target codes can be generated.


? # If... # Else... # Endif is processed by the Pre-compiler, while if... The else statement is
Compiler processing must be compiled into the target code


? In actual projects, Conditional compilation is mainly used in the following two situations:
? Different product lines share one piece of code
? Differentiate between debugging and release versions of compiled Products

Summary
? Use the compiler command line to define the macros used by the pre-processor
? Conditional compilation can avoid repeated inclusion of the same header file.
? Conditional compilation is the code that can differentiate different product lines in engineering development.
? Conditional compilation defines the release and debugging versions of the product.

Break usage

The break keyword can be used to exit a loop by condition. When the condition of break is met, the loop is directly exited, instead of judging the loop condition and increasing or decreasing the variable.

Procedure

To implement this case, follow these steps.

Step 1: The break usage code is as follows:

# Includeint main () {for (int I = 0; I ++) {int num; printf ("enter an integer (enter 0 to exit ):"); scanf ("% d", & num); if (num> 0) printf ("% d is a positive number. \ N ", num); else if (num <0) printf (" % d is a negative number. \ N ", num); elsebreak;} return 0 ;}
  1.  

In the above Code, the following code:

  1. For (int I = 0; I ++)

Set an endless loop.

In the above Code, the following code:

  1. Int num;
  2. Printf ("enter an integer (enter 0 to exit ):");
  3. Scanf ("% d", & num );

First, define an integer variable num to store an input integer.

Then, use the printf function to prompt for an integer and enter 0 to exit.

Finally, use the scanf function to input an integer to the variable score.

In the above Code, the following code:

  1. If (num> 0)
  2. Printf ("% d is a positive number. \ N ", num );

If the input integer is greater than 0, the print is a positive number.

In the above Code, the following code:

  1. Else if (num <0)
  2. Printf ("% d is a negative number. \ N ", num );

If the input integer is smaller than 0, the print is a negative number.

In the above Code, the following code:

  1. Else
  2. Break;

If the input integer is equal to 0, the loop is exited. The break statement can be used to achieve an indefinite number of cycles.

Complete code

The complete code for this case is as follows:

# Includeint main () {for (int I = 0; I ++) {int num; printf ("enter an integer (enter 0 to exit ):"); scanf ("% d", & num); if (num> 0) printf ("% d is a positive number. \ N ", num); else if (num <0) printf (" % d is a negative number. \ N ", num); elsebreak;} return 0 ;}
  1.  
An uncertain number of loops

Implement a "guess number" game.

Procedure

To implement this case, follow these steps.

Step 1: loop with an uncertain number of cycles

# Include # includeint main () {srand (time (0); int ran = rand () % 100 + 1; for (;) {int num; printf ("enter an integer between 1 and 100:"); scanf ("% d", & num); if (num <0 | num> 100) printf ("the number of inputs is not between 1 and 100. \ N "); else if (num = ran) break; else if (num> ran) printf (" Big \ n "); elseprintf (" \ n");} printf ("guessed \ n"); return 0 ;}
  1.  

In the above Code, the following code:

  1. Srand (time (0 ));

Set random algorithm seed. This sentence is required to use a random number.

In the above Code, the following code:

  1. Int ran = rand () % 100 + 1;

Use the rand function to generate a 1 ~ A random number between 100.

In the above Code, the following code:

  1. For (;;)

Set an endless loop.

In the above Code, the following code:

  1. Int num;
  2. Printf ("enter an integer between 1 and 100 :");
  3. Scanf ("% d", & num );

First, define an integer variable num for storing input 1 ~ An integer between 100.

Then, use the printf function to prompt you to enter an integer.

Finally, use the scanf function to input an integer to the variable score.

In the above Code, the following code:

  1. If (num <0 | num> 100)
  2. Printf ("the number of inputs is not between 1 and 100. \ N ");

Fault Tolerance protection. The input integer is not 1 ~ Between 100, then re-enter.

In the above Code, the following code:

  1. Else if (num = ran)
  2. Break;

If the entered integer is exactly the same as the random number, exit with the break statement.

In the above Code, the following code:

  1. Else if (num> ran)
  2. Printf ("Big \ n ");

If the input integer is greater than the random number, a large value is displayed.

In the above Code, the following code:

  1. Else
  2. Printf ("Small \ n ");

If the input integer is smaller than the random number, the prompt is smaller.

In the above Code, the following code:

  • Printf ("guessed \ n ");

After you exit the loop using the break statement, you are prompted to guess it.

Complete code

The complete code for this case is as follows:

# Include # includeint main () {srand (time (0); int ran = rand () % 100 + 1; for (;) {int num; printf ("enter an integer between 1 and 100:"); scanf ("% d", & num); if (num <0 | num> 100) printf ("the number of inputs is not between 1 and 100. \ N "); else if (num = ran) break; else if (num> ran) printf (" Big \ n "); elseprintf (" \ n");} printf ("guessed \ n"); return 0 ;}
  1.  
Continue usage Problems

The continue keyword can be used to abort this loop based on conditions and continue the next loop. The break exits the loop. The continue does not exit the loop, but does not continue to execute this loop.

Procedure

To implement this case, follow these steps.

Step 1: The usage code of continue is as follows:

#includeint main(){for (int i = 0; i <= 100; i++)if(i % 2)continue;elseprintf("%d ", i);printf("\n");return 0;}

In the above Code, the following code:

  1. For (int I = 0; I <= 100; I ++)

Set a loop for 100 times.

In the above Code, the following code:

  1. If (I % 2)
  2. Continue;
  3. Else
  4. Printf ("% d", I );

Judge the cyclic variable. If the cyclic variable is an odd number, use the continue statement to continue the loop. Otherwise, print the even number.

Complete code

The complete code for this case is as follows:

#includeint main(){for (int i = 0; i <= 100; i++)if(i % 2)continue;elseprintf("%d ", i);printf("\n");return 0;}
  1.  
Dual Loop usage Problems

Print the image shown in-2:

Figure 2

Procedure

To implement this case, follow these steps.

Step 1: use the code of the double loop as follows:

#includeint main(){for (int i = 0; i < 5; i++){for (int j = 0; j <= i; j++)printf("*");printf("\n");}return 0;}
  1.  

In the above Code, the following code:

  1. For (int I = 0; I <5; I ++)

Set an outer loop. The loop is 5 times, indicating that five rows are printed.

In the above Code, the following code:

  1. For (int j = 0; j <= I; j ++)
  2. Printf ("*");

Set an inner loop. The number of cycles is determined by the outer loop variable I. When I is equal to 0, A * is printed. When I is equal to 1, two * is printed, and so on.

We can see how many rows are printed in the outer loop and how many rows are printed in the inner loop *.

In the above Code, the following code:

  1. Printf ("\ n ");

This sentence is very important, because when the inner loop exits, it indicates that the * of a row has been printed. At this time, you need to print a carriage return to wrap the line.

Complete code

The complete code for this case is as follows:

#includeint main(){for (int i = 0; i < 5; i++){for (int j = 0; j <= i; j++)printf("*");printf("\n");}return 0;}
  1.  
Use of double loop (Continued 1)

Print the image shown in-3:

Figure-3

Procedure

To implement this case, follow these steps.

Step 1: Use the switch statement

The Code is as follows:

  1. # Include
  2.  
  3. Int main ()
  4. {
  5. For (int I = 0; I <5; I ++)
  6. {
  7. For (int j = 0; j <= I * 2; j ++)
  8. Printf ("*");
  9. Printf ("\ n ");
  10. }
  11.  
  12. Return 0;
  13. }

In the above Code, the following code:

  1. For (int I = 0; I <5; I ++)

Set an outer loop. The loop is 5 times, indicating that five rows are printed.

In the above Code, the following code:

  1. For (int j = 0; j <= I * 2; j ++)
  2. Printf ("*");

Set an inner loop. The number of loops is determined by the inner loop variable I * 2. When I is equal to 0, the condition is j <= 0, so a * is printed once in a loop *. When I is equal to 1, the condition is j <= 1*2, so three times are cyclically printed, and so on.

We can see how many rows are printed in the outer loop and how many rows are printed in the inner loop *.

In the above Code, the following code:

  1. Printf ("\ n ");

This sentence is very important, because when the inner loop exits, it indicates that the * of a row has been printed. At this time, you need to print a carriage return to wrap the line.

Complete code

The complete code for this case is as follows:

#includeint main(){for (int i = 0; i < 5; i++){for (int j = 0; j <= i * 2; j++)printf("*");printf("\n");}return 0;}
  1.  

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.