[Linux] "Linux C programming stop learning" [C language] Getting Part.1

The basic concept of the program

  • And programming languages
    • C language - (compiler) - Assembly Language - (assembler) - the machine language (object code / executable code)
    • Portable / platform-independent: it refers to a combination of computer platform or operating system architecture, or both. Different platforms have different instruction set, instruction format different recognition machine
    • Write directly to some computer assembler or machine instructions out of the program is only available on computers that run on a variety of computer has C compiler can compile the C program into their computer machine instructions
    • Compiled / interpreted language: language interpreted without generating object code, executed by an interpreter, line by line, translate and
  • Natural language and formal language
    • Natural language is spoken human language, such as Chinese, English, French
    • Formal language for specific applications considered design language, such as mathematical symbols, molecular formula, programming languages
    • There are strict formal language syntax (Syntax) Rules
    • There are rules about grammar rules sign (Token) and structure (Structure) are composed of
    • Symbol: pre-defined operators, lexical rules on symbols is (, Lexical) Rule
    • Structure: arrangement of symbols on a regular structure grammar (Grammar) rules
    • Parsing (Parse): sentence structure analysis process
    • The difference between natural language and formal language
      • Ambiguity (Ambiguity): the formal language of design requirements for clear, unambiguous, each statement has a clear meaning regardless of context
      • Redundancy (Redundancy): Natural Language to disambiguate the introduction of redundancy, redundancy little formal language
    • Consistency literal meaning: natural language full of metaphor (Metaphor), in the form of language that is literally true meaning
    • Suggested Reading formal languages ​​(including computer programs)
      • In the form of natural language than the language of the compact, spend time reading
      • The structure is very important, do not read from top to bottom or left to right, but should be resolved in the brain, identify the Token, Breakdown Structure
      • Attention to detail, such as spelling errors and symbol errors
  • Debugging
    • Bug Classification
      • Compile-time error: syntax error compilation fails
      • Run-time error: compiler checks not, but the error causing the program to crash (note the distinction between the two concepts compile-time and run-time) runtime
      • Logical errors and semantic errors: compile and run very smoothly, but did not achieve the expected results
    • Programming Advice
      • Programming = Debug: Debug until the program is to gradually achieve the desired result
      • Always start from a small-scale program to run properly, make every small step changes immediately debugging

Constants, variables, and expressions

  • Definition, assignment, initialization
    • Definition: allocating a memory space and give it a name, such as int hour;
    • Assignment: the value stored in a memory space, such as the hour = 11;
    • Initialization: + assignment defined as int hour = 11;
  • Initialization is a special variable definition statement, not assignment
  • In addition to the variable name with the left side of the equal sign represents the assignment, the other cases are taken out represents its value, where replacement
  • Expression (Expression) by the operator (the Operator) and operands (the Operand) Composition
  • Assignment statement is an expression of
  • Operators have priority (Precedence), such as undesirable by default priority calculation need parentheses (Parenthesis)
  • The results of C language provision equals operator is the value of the left side of the equal sign is given
  • Constants can be assigned to variables, and may be variables, operators together form expression
  • The simplest expression of a single constant or variable composition
  • Any expression has a value, an expression can be added; No. constitute expression statement

Simple function

  • is a function of sin (Function), sin (pi / 2) is a function call (Function Call), pi / 2 is the parameter (the Argument)
  • Function call sin (pi / 2) is the expression by the function call operator () and two operands, the return value of the function value of the expression (Return Value)
  • C language function can have side effects (Side Effect), which is the fundamental difference between it and the mathematical functions on the concept of
  • The expression a = b, the return value is a value, the value of a side effect is changed
  • Many times we are concerned about side effects of function, rather than the return value, such as printf (), the return value is the number of characters actually printed, rather than print
  • Side Effect fully utilized for the function can be defined as the return value void
  • Function Prototype (Prototype): function name and number of the parameter type + + Return Type
  • Function first statement after use
  • When the column can define a variable with the same type of a variable, but not the definition of function parameters, such as void print_time (int hour, minute) {}; wrong wording
  • Parameter (the Parameter) corresponding to the variables defined in the function, the function call corresponds to the process of the transmission parameters is defined by the value of parameter variables and arguments (the Argument) to initialize
  • Function provides an interface (Interface), the calling function is to use this interface, using the premise that the interface must be consistent
  • Function parameter passing can not use global variables in place of
  • Global variables can only be initialized with a constant expression, and local variables can be initialized with any type of expression
  • C language predetermined initial value of the global variable stored in the compiled object code, it can be calculated out when compiled, such as global variables initialization statement pi double pi = 3.14 + 0.0016; is legal, and double pi = acos ( -1.0); it is not legitimate
  • If the global variable is not defined at the time of initialization, the initial value is 0 (or "\ 0" or "0.0", etc.)
  • Local variables are not initialized on the definition, the initial value of uncertainty, you must first assign local variables before use
  • Local variables of storage space allocated each function call, the function returns released

Branch statement

  • Local variables storage space is allocated at each entry statement block, a block of statements released upon exit
  • Statement of the package as a function of the steps of: the statements in the body of the function, the function of the variable parameter into
  • else always the nearest one if its top pair
  • Behind the case with must be a constant expression, similar to global variables, you must calculate the value at compile time

In-depth understanding of the function

  • Define equivalent function return value and a type of function return the same value temporary variable, and use the latter to initialize return expression
  • The return value is not an lvalue, you can not assign to it
  • When writing a function with a return statement, be careful to check that all code paths (Code Path), under any conditions unreachable code called Dead Code
  • Incremental development (Incremental): as far as possible reuse (Reuse) the code written before, avoid writing duplicate code. Package is to reuse

loop statement

  • And the difference between the two ways of recursive cycles: recursively by recursion relations (!! Such as n = n * (n-1)), the formula loop is expanded (e.g., n = n * (n-1) * (n-2! ) ... 3 * 2 * 1). Expansion formula easier to understand, but can not expand when the formula is too complicated, even more intuitive recursive
  • Recursion is assigned throughout the process and release a lot of variables, but all variables are only assigned at initialization time, there is no value of any variable change occurred, and the cycle is repeated by assigning several variables to achieve their goals
  • Recursive function called programming ideas (Functional Programming), the idea is called imperative programming cycle (Imperative Programming)
  • What do recursive description (Declarative), describe the specific cycle step by step how to do (Imperative)
  • Functional programming "function" is similar to the concept of mathematical functions, is of no Side Effect, Imperative way to a variable number of changes can cause problems, such as thread-safe code impact, it should be in a "consistent" way multiple assignments
  • do / while statement to add a semicolon after the while statement
  • ++ i: pass parameters, return value (parameter +1), Side Effect: value of the variable i +1
  • i ++: pass parameters, return value (parameter), Side Effect: value of the variable i +1
  • goto: unconditional jump, jump to a label can only be at the same function, but can not jump to another function in
  • goto statement only for functions that handle the end of the error function anywhere there has been an error condition can immediately jump to the end, the function returns after treatment

Structure

  • Data abstraction: similar to "extract common factor", ab + ac = a (b + c), if a left changed, two factors should be modified, as long as the right to change a factor
  • Any combination of such systems can be complex, so that the complexity of the system and abstract is controllable, any changes only limited to a certain level, and will not affect the entire system
  • All problems in computer science can be solved by another level of indirection(abstraction)--Butler Lampson
  • By storing a plurality of spaced showing the storage format of the abstraction layer structure and an upper complex_struct complex operation function
  • Enumeration type: a structure allows for receiving different types of input, such as enum coordinate_type {RECTANGULAR, POLAR}; struct complex_struct {enum coordinate_type t; double a, b;} ;, by defining a data type identifier, such Cartesian and polar coordinates data can be adapted to the structural body complex_struct

Array

  • Array (the Array) is a complex data type, a series of the same type of element (Element) Composition
  • Use array subscript range can not exceed the length of the array, C compiler does not check array bounds error
  • And an array of different structures: the array can not be assigned to each other, not as a function of the parameters or return values
  • When using the array name do rvalue, automatically converted into a pointer pointing to the first element of the array
  • Use the C standard library to get a random number is actually a pseudo-random number (Pseudorandom), but looks very random, and the result is the same for each run
  • Get an indeterminate number of other ways as Seed, and then generates a pseudo-random number on this basis, as srand (time (NULL)); (number of seconds January 1 1970 00:00:00 Current time drama)
  • Using the rand () to generate a pseudo-random number, the header file stdlib.h, the return value is an integer between 0 and RAND_MAX, RAND_MAX is a constant defined in the header file, if you want to define the number of available random process% within a certain range, the int x = rand (% 10); (random number in the 0 to 9)
  • define the preprocessing stage process, avoids hardcoded (Hard coding) (abstract Similarly, to avoid a large local changes spread range)

String

  • Can be seen as a string array element is character, and at the end of a character "\ 0" indicates the end of the string. String is read-only, can not be modified
  • Doing the right value to use, automatically converted into a pointer pointing to the first element
  • When initialization string, may designate the array length, and let the compiler automatically calculated
  • Data-driven programming (Data-driven Programming): programming the most important thing is to choose the right data structure to organize information, control processes and algorithms still followed, as long as the correct data structure is selected, the code is easy to understand and maintain the natural

Coding Style

  • Code is mainly to write on posters, but also use the machine to perform the way it
  • Linux kernel CodingStyle
    • Reflect the hierarchy by indenting statement blocks (Tab)
    • if / else, while, for other blocks can take the statement Statement,} and {statement block should be written with the keywords separated by a space, instead of a separate line
    • Functions defined on a separate line} and {
    • switch and a block of statements in the case, default aligned write
    • Each logical code by a blank line between paragraphs spaced apart
    • Packet according to the correlation, the function separated by an empty line
  • Note
    • The entire top of the source file Note: file name, author, version history
    • NOTE function: function functions, parameters, return values, error code
    • Statement Note: written on the side of the statement
    • Code Short Notes: Write between the right codes, and code separated by a space at least, all of the source file is preferably aligned vertically right annotations
    • Notes to function within as little as possible, only shows what code can do, rather than how to do it (as long as the code is clear, how to do is clear, otherwise the code readability is poor)
    • Complex structure, macro definitions and variable definitions need to comment
  • variable
    • Clarity, we can complete all easy to understand words and abbreviations
    • Variables, function types using all lowercase underlined constants (macros and enumerate) all-uppercase underlined
    • Hungarian notation with caution, not Pinyin
  • function
    • Do one thing at a function
    • Internal function indentation level of no more than four layers
    • Do not write too long function
    • Execution function is to perform an action, function names should normally contain a verb
    • Not too many local variables
  • indent tool: the code can be formatted in a certain style

gdb

  • Commissioning steps: analysis of the phenomenon -> assume the wrong reasons -> generate new phenomena test hypotheses
  • Single-step execution and tracking function calls
  • Breakpoint (Breakpoint)
  • Observation point (Watchpoint): a storage unit does not know where to be altered
  • Segment error: access violation occurs if a function, it may not produce an immediate segmentation fault segment generated an error when the function returns

Sort and Find

  • The method of determining correctness loop Loop Invariant
    • Before performing the first determination condition is true the loop
    • If the "N-1 after the first cycle to determine the condition is true," the premise is established, you can prove that N cycles after the first judgment condition remains true
    • After all the cycle to determine the condition is true, then the algorithm correctly

Stacks and queues

  • Data storage, access method determines a problem to solve the problem of what algorithms can be used, at the same time we must design algorithm design appropriate data structures to support this algorithm
  • Stack - LIFO - depth-first search (DFS) - backtracking (Backtrack)
  • Queue - First In First Out (FIFO) - breadth-first search (BFS)

 

reference

http://docs.linuxtone.org/ebooks/C&CPP/c/

Guess you like

Origin www.cnblogs.com/cxc1357/p/12356222.html