C Language Concept Summary

Source: Internet
Author: User

1. Differences between reference and pointer:

1) The reference must be initialized, And the pointer does not have;

2) The reference cannot be changed after initialization, And the pointer can change the object referred.

3) There is no reference pointing to a null value, but there is a pointer pointing to a null value null.

After a pointer variable points to an object, it indirectly operates on the variable it points. When pointers are used in a program, the program has poor readability. The reference itself is the alias of the target variable, and the reference operation is the operation of the target variable.

2. Basic Features of a Real-Time System: complete specific tasks within a specific period of time, real-time and reliability.

3. balanced binary tree: both left and right Subtrees are balanced binary trees, and the absolute value of the depth difference between left and right Subtrees is not greater than 1.

4. Cause of stack overflow: 1. No garbage collection resources are collected. 2. recursive calls with too deep layers

5. What functions cannot be declared as virtual functions: Constructor

Constructor, because it is called before the object is generated, and the virtual function is a mechanism that takes effect after the object is generated, it is meaningless to declare the virtual constructor.

6. If statement for comparing variables with "zero value:

Bool: If (! A) or if ()
INT: if (a = 0)
Float: const expressions exp = 0.000001
If (A>-exp & A <exp)
Pointer: if (! = NULL) or if (a = NULL)

 

7 program memory allocation
A: The Memory occupied by a C/C ++ compiled program is divided into the following parts:
1. STACK: the stack is automatically allocated and released by the compiler, and stores the function parameter values and local variable values. The operation method is similar to the stack in the data structure and is automatically destroyed when the function returns.
2. Heap: Generally, it is assigned and released by programmers. If the programmer does not release the heap, it may be recycled by the OS at the end of the program (it must be destroyed after use to prevent memory leakage ). Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.
3. global (static)-the storage of global variables and static variables is put together, and the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. The program is released by the system.
4. Text Constant Area-constant strings are placed here. The program is released by the system.
5. program code area-stores the binary code of the function body

Example Program
// Main. cpp
Int A = 0; // global initialization Zone
Char * P1; // not initialized globally
Main ()
{
Intb; stack
Char s [] = "ABC"; // Stack
Char * P2; // Stack
Char * P3 = "123456"; // 123456 \ 0 is in the constant zone, and P3 is in the stack.
Static int C = 0; // global (static) initialization Zone
P1 = (char *) malloc (10 );
P2 = (char *) malloc (20); // The allocated 10-byte and 20-byte areas are in the heap area.
Strcpy (P1, "123456"); // 123456 \ 0 is placed in the constant area, and the compiler may optimize it to "123456" as directed by P3.
}

8. Differences between heap and stack

(1) Application Method
STACK: automatically assigned by the system. For example, declare a local variable int B in the function; the system automatically opens up space for B in the stack.
Heap: requires the programmer to apply for and specify the size. In C, the malloc Function
For example, P1 = (char *) malloc (10 );
Use the new operator in C ++
For example, P2 = (char *) New (10 );
But note that P1 and P2 are in the stack.

(2) system response after application
STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application,
The linked list is traversed to find the heap node with the first space greater than the requested space. Then, the node is deleted from the idle node linked list and allocated to the program, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.

(3) Application size limit
STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the top stack address and the maximum stack capacity are pre-defined by the system. If the requested space exceeds the remaining stack space, overflow is prompted. Therefore, the space available from the stack is small.
Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.

(4) Comparison of application efficiency:
STACK: the stack is automatically allocated by the system, and the speed is fast. But programmers cannot control it.
Heap: Memory allocated by new. It is generally slow and prone to memory fragments. However, it is most convenient to use.
In addition, in windows, the best way is to use virtual alloc to allocate memory. It is not in the heap, nor in the stack, but to reserve a piece of memory directly in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.

(5) Storage content in heap and stack
STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note that static variables are not included in the stack.
When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.
Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.

9malloc and new:

1. malloc and free are standard library functions of C ++/C, and new/delete are operators of C ++. They can be used to apply for dynamic memory and release memory.
2. For non-Internal data objects, the use of maloc/free alone cannot meet the requirements of dynamic objects. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free.
3. Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory. Note that new/delete is not a database function.
4. c ++ programs often call C functions, while C Programs can only use malloc/free to manage dynamic memory.

5. New can be considered as the execution of the malloc and constructor. The new pointer directly carries the type information. Malloc returns the void pointer.

6. New automatically calculates the space to be allocated, while malloc manually calculates the number of bytes.
7. New is type-safe, but malloc is not. For example:
Int * P = new float [2]; // indicates an error during compilation
Int * P = malloc (2 * sizeof (float); // The error cannot be specified during compilation.

8. Memory leakage can be checked out for malloc or new. The difference is that new can indicate the row of the file, and malloc does not have this information.

10 constructor and destructor

Constructor is a special member function of a class. It has the same name as the class name. When an object of this class is defined, the constructor is automatically called by the system to initialize the object.
The constructor cannot return values. Therefore, it cannot specify any types of return values including void.
The definition of constructor can be placed inside or outside the class like that of other member functions.
The Definition Format of the constructor is:
Class Name (parameter description)
{Function body}
The constructor can be defined as either a parameter-free function or a non-argument function, depending on the needs of the problem.
Note: constructor cannot be called directly in a program. The constructor is called directly by the system when an object is created. Therefore, the initialization of class member variables is generally completed in the constructor.

Destructor
The constructor corresponds to the destructor. When an object is defined, the system automatically calls the constructor to allocate resources to the object. After the object is used up and before the object disappears, the system automatically calls the class destructor to release these system resources.
The Destructor is also a special member function of the class. The function name is preceded by the class name "~"; It has no return value or parameter. A class can have only one destructor, so the Destructor cannot be overloaded.
The Destructor is defined as follows:
~ Class Name ()
{Function body}
If the programmer does not provide destructor for the class when defining the class, the system automatically creates a default destructor in the form:
~ Class Name ()
{}
The order in which objects are destructed is the opposite of the order in which they are created, that is, the last constructed object is first destructed.
If an object is dynamically created by the new operator, when the delete operator is used to release it, delete automatically calls the destructor.

11 function Overloading

The same function name can correspond to the implementation of multiple functions. Each implementation corresponds to a function body. These functions have the same name, but their parameters or types are different. This is the concept of function overloading. Function overloading requires the compiler to uniquely determine which function code should be executed when a function is called, that is, which function is used for implementation. When determining the function implementation, the number and type of function parameters must be distinguished. This means that during function overloading, functions with the same name are required to have different numbers of parameters or different parameter types. The Compiler performs optimal matching based on the type and number of real parameters, automatically determines which function to call. Otherwise, overload cannot be implemented.

12. function re-import

The reentrant function is mainly used in a multi-task environment. A reentrant function is simply a function that can be interrupted, that is, it can be interrupted at any time during the function execution, when the system is transferred to the OS for scheduling and another piece of code is executed, no error will occur when the returned control is returned. The non-reentrant function uses some system resources, such as the global variable area, interrupt vector table, etc. Therefore, if it is interrupted, problems may occur. Such functions cannot run in multi-task environments.

Re-entry means repeated entry. First, it means that this function can be interrupted. Second, it means that it does not depend on any environment (including static) except the variables on its own stack ), such a function is a purecode (pure code) reentrant, which allows multiple copies of the function to run. Since they use a separate stack, they do not interfere with each other. If you really need to access global variables (including static), be sure to implement mutex.

13 pre-compile

Pre-compilation, also known as preprocessing, is the replacement of some code text. Processing commands starting with #, such as copying the file code contained in # include, # replacement of the define macro definition, and Conditional compilation, is the stage of preparation for compilation, main Processing # pre-compilation commands started. Pre-compilation commands indicate the operations performed by the compiler before the program is officially compiled. They can be placed in any position in the program.

C compilation system pre-processes programs before they are normally compiled. C provides the following preprocessing functions: 1) macro definition # define 2) File Inclusion # include 3) Conditional compilation # If, # else, And # endif

1. Always use large code bodies that are not frequently modified.

2. A program consists of multiple modules. All modules use a set of standard inclusion files and the same compilation options. In this case, all contained files can be precompiled into a precompiled header.

13 Differences Between inline functions and macro definitions

(1) inline functions are available during compilation and macros are available during pre-compilation;

(2) inline functions are directly embedded into the target code, and macros are simple for text replacement;

(3) inline functions include type detection and syntax judgment, but macros do not;

(4) The inline function is a function, and the macro is not;

(5) Pay attention to writing macro definitions (including parameters); otherwise, ambiguity may occur, and inline functions will not produce ambiguity.

The difference between 14const and macro constants:

1) const constants have data types, while macro constants do not.

The compiler can perform type security checks on the former, while the latter can only replace characters without security checks, and unexpected errors may occur when replacing characters.

2) compiler debugging

Some integrated debugging tools can debug const constants. In C ++ programs, only const constants are used instead of macro constants, that is, const constants completely replace macro constants.

 

15 differences between arrays and pointers

An array is either created in a static storage area (such as a global array) or on a stack. Pointers can point to any type of memory block at any time.
Char A [] = "hello ";
Char * P = "world"; // note that P points to a constant string

(1) Differences in modification content
A [0] = 'X ';
P [0] = 'X'; // This error cannot be found by the compiler. It is a runtime error.
(2) the sizeof operator can be used to calculate the array capacity (number of bytes ). Sizeof (P), P is the number of bytes of a pointer variable, rather than the memory capacity referred to by P. C ++/C language cannot know the memory capacity referred to by the pointer unless you remember it when applying for memory. Note: When an array is passed as a function parameter, the array will automatically degrade to a pointer of the same type.
Sizeof (a) // 6 bytes
Sizeof (p) // 4 bytes

There are four differences between 16define and typedef:
1. Different usage
Typedef is used to define an alias for a data type to enhance program readability;
Define is mainly used to define constants and is expected to write complex and frequently used expressions.

2. Different execution times
Typedef has no memory space allocated, is replaced during preprocessing, and has the type check function;
Define is a macro definition, which is replaced during preprocessing. It is a simple string replacement and does not check the type.

3. different scopes
Typedef has a limited scope;
Define has no limitations on scope, as long as the references are correct after define's reputation. For example:

4. Different pointer operations
For example, # define pchar * and # typedef pchar * are two concepts.

What is the difference between 17C and C ++?
Mechanism: C is process-oriented (but C can also write Object-oriented Programs); C ++ is object-oriented and provides classes. However,
C ++ is easier to write object-oriented programs than C
From the applicable direction: C is suitable for scenarios that require small code size and high efficiency, such as embedded; C ++ is suitable for upper-level and complex; llinux is mostly written in C, because it is system software, the efficiency requirement is extremely high.
From the name, we can see that C ++ is more + than C, which means C ++ is the superset of C. Why is C ++ not called C ++, because of the C ++ Ratio
C, there are too many extended things, so I put two + s behind C, so it became C ++
C is a structured programming language, and C ++ is an object-oriented programming language.
C ++ focuses on objects rather than processes, and on class design rather than logic design.

18 0, '0', "0", '\ 0.
The values are 0, the characters are 0 (the ASCII code value is 48), and the strings are 0 (which occupies two bytes and uses '\ 0' as the terminator ), string end sign (the value equal to 0 is absolute 0, but the meaning is different)

19 array of pointer Functions

A) An integer)

Int A; // an integer

B) a pointer to an integer (a pointer to an integer)

Int * A; // a pointer to an integer

C) a pointer to a pointer pointing to an integer (a pointer to an integer)

Int ** A; // a pointer to an integer

D) an array of 10 integers (an array of 10 integers)

Int A [10]; // an array of 10 Integers

E) an array with 10 pointers pointing to an integer (an array of 10 pointers to integers)

Int * A [10]; // an array of 10 pointers to Integers

F) A pointer to an array with 10 integers (a pointer to an array of 10 integers)

INT (* A) [10]; // a pointer to an array of 10 Integers

G) a pointer to a function. The function has an integer parameter and returns an integer number (a pointer to a function that takes an integer as an argument and returns an integer)

INT (* A) (INT); // a pointer to a function a that takes an integer argument and returns an integer

H) An array with 10 pointers pointing to a function, this function has an integer parameter and returns an integer (an array of ten pointers to functions that take an integer argument and return an integer)

INT (* A [10]) (INT); // an array of 10 pointers to functions that take an integer argument and return an integer

20 address alignment

In modern computers, memory space is divided by byte. Theoretically, it seems that access to any type of variables can start from any address, however, the actual situation is that access to specific variables is often performed at specific memory addresses, which requires various types of data to be arranged in space according to certain rules, this is the alignment instead of the sequential one-by-one arrangement.

Alignment functions and causes: the processing of storage space varies greatly by hardware platform. Some platforms can only access certain types of data from some specific addresses. Other platforms may not have these restrictions, but the most common problem is that alignment of data storage according to the requirements suitable for their platforms will result in a loss of access efficiency. For example, some platforms start from an even address each time they read data. If an int type (assuming 32 bits) is stored at the beginning of an even address, a clock cycle can be read. If it is stored at the beginning of an odd address, two clock cycles may be required, and the high and low bytes of the two read results can be pieced together to obtain the int type data. Obviously, reading efficiency is greatly reduced. This is also a game of space and time.

Divided into: byte alignment, semi-word alignment, Word Alignment

21 assert () macro usage

When writing code, we always make some assumptions. assertions are used to capture these assumptions in the Code and can be seen as an advanced form of exception processing. Assertions are expressed as boolean expressions. The programmer believes that the expression value is true at a specific point in the program. You can enable and disable Assertion Verification at any time, so you can enable assertion during testing and disable assertion during deployment. Similarly, after the program is put into operation, the end user can re-use the assertions in case of problems.

Assert is used to terminate program execution if its condition returns an error. The expression is calculated first. If its value is false (0 ), it first prints an error message to stderr, and then calls abort to terminate the program running.

The disadvantage of using assert is that frequent calls will greatly affect program performance and increase additional overhead.

Usage summary and precautions:

1) Check the validity of input parameters at the beginning of the Function

Each assert tests only one condition, because when multiple conditions are verified at the same time, if the assert fails, you cannot intuitively determine which condition fails.

3) You cannot use statements that change the environment, because assert only takes effect in debug. If so, problems will occur when the program is actually running.

4) assert and the following statement should be empty for logical and visual consistency.

5) In some cases, assert cannot replace conditional filtering. Assert is used to avoid obvious errors rather than handling exceptions. Errors are different from exceptions. Errors should not occur and exceptions are inevitable. C language exceptions can be handled through condition judgment. Other languages have their own exception handling mechanisms.
22. leaf function: a function that does not call other functions internally. Non-leaf function: a function that calls other functions internally. The non-leaf function saves the return address to the stack of the parent function at the beginning of the function, and reads and returns the address at the end of the function. This gives us a chance to take advantage of the function, but the leaf function does not. When a non-leaf function is input, the return address of the function is stored in the stack frame identification area of the parent function. The returned address is then obtained and returned. 23 branch prediction: an advanced data processing method starting from the P5 era to handle pipeline failures caused by branch commands (if-then-else, the CPU determines the direction of the program Branch, which can speed up the operation. Principle: When the processor containing the assembly line technology processes branch commands, it will encounter a problem. Based on the true/false judgment conditions, there may be a jump, this interrupts the processing of commands in the pipeline, because the processor cannot determine the next command of the command until the branch execution is complete. The longer the assembly line, the longer the processor will wait, because it must wait for the processing of the branch command to complete the next command to enter the assembly line. The branch prediction technology is designed to solve this problem. The branch prediction technology includes Static branch prediction during compilation and dynamic branch prediction during hardware execution. Static branch prediction: the simplest Static branch prediction method is to select one branch. In this way, the average hit rate is 50%. The more accurate method is to make statistics based on the original running results to try to predict whether the branch will jump. The effect of any branch prediction policy depends on the accuracy of the policy and the frequency of the condition branch. Dynamic branch prediction: a technology that has recently been used by processors. The simplest dynamic branch prediction strategy is branch prediction buff or branch history table ).

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.