C/C++ common knowledge points and summary of interview questions (updated from time to time)

Organizing this article is mainly for my own summary of the concept of C/C++. The content sources are roughly distributed on the Internet, "C++ Primer Plus" and "Effective C++", etc. Many big cows have already made good summaries, and the reference link will be given at the end of the article.

1. Computer Basics

1. What are the types of C/C++ memory?

In C, memory is divided into 5 areas: heap (malloc), stack (such as local variables, function parameters), program code area (store binary code), global/static storage area (global variables, static variables) and constant storage area (constant). In addition, there is a free storage area (new) in C++.
Global variables and static variables are initialized to default values, while variables on the heap and stack are random and uncertain.

2. What is the difference between heap and free storage area?

  • In general, the heap is a term of the C language and operating system, and is a piece of dynamically allocated memory maintained by the operating system; free storage is an abstract concept in C++ that dynamically allocates and releases objects through new and delete. They are not exactly the same.
  • Technically speaking, heap is a term of C language and operating system. The heap is a special memory maintained by the operating system. It provides the function of dynamic allocation. When the running program calls malloc(), it will be allocated from it, and free can be called later to return the memory. And free storage is an abstract concept in C++ that dynamically allocates and releases objects through new and delete. The memory area applied for through new can be called a free storage area. Basically, all C++ compilers use the heap to achieve free storage by default, that is, the default global operators new and delete may be implemented in the manner of malloc and free. At this time, the objects allocated by the new operator , It is correct to say that it is on the heap, and it is correct to say that it is on the free storage area.

3. The difference between heap and stack?

  1. The heap stores dynamically allocated objects —that is, those objects that are dynamically allocated when the program is running, such as new objects, whose lifetime is controlled by the program;
  2. The stack is used to save the non-static objects defined in the function, such as local variables , which only exist when the program block defined by it is running;
  3. Static memory is used to store static objects, class static data members and variables defined outside any function. Static objects are allocated before use and destroyed when the program ends;
  4. Objects in the stack and static memory are automatically created and destroyed by the compiler.

4. What is the process of program compilation?

The process of program compilation is the process of converting the user's textual source code (c/c++) into machine code that can be directly executed by the computer. There are four main processes: preprocessing, compilation, assembly and linking .

A C language program of hello.c is as follows.

#include <stdio.h>
int main()
{
    
    
    printf("happy new year!\n");
    return 0;
}

Insert picture description here

5. How to store negative numbers and floating-point numbers inside the computer?

  • Negative numbers are easier, which is represented by a flag bit and one's complement.
  • For floating-point data, single-precision type (float) and double-precision type (double) are used for storage. Float data occupies 32bit, and double data occupies 64bit. When we declare a variable float f = 2.25f, how to allocate memory What about? If the allocation is random, isn't the world messed up? In fact, both float and double are stored in compliance with IEEE specifications. Float complies with IEEE R32.24, and double complies with R64.53. More can refer to floating-point number representation.
  • Both single-precision and double-precision are divided into three parts in storage:

1). Sign bit (Sign): 0 means positive, 1 means negative
2). Exponent: used to store exponent data in scientific notation, and use shift storage
3). Mantissa part (Mantissa) : Mantissa part

The storage method of single-precision float is as follows: the storage method of
Insert picture description here
double-precision double is as follows:
Insert picture description here

6. Left and right values?

  • In a less rigorous way, lvalue refers to a variable (or expression) that can appear both on the left and on the right of the equal sign, and rvalue refers to a variable (or expression) that can only appear on the right of the equal sign ( Or expression).
int a = 1;     //a是一个左值
int b = 2;     //b是一个左值
int c = a + b; //+需要右值,所以a和b都转换成右值,并且返回一个右值

7. What is a memory leak? In the face of memory leaks and pointer out-of-bounds, what methods do you have? What methods do you usually use to avoid and reduce such errors?

The space dynamically opened up by the dynamic storage allocation function is not released after use . As a result, the memory unit is always occupied, which is a memory leak.

1). Remember the length of the pointer when using it.
2). Make sure to be free when using malloc; remember to delete when using new.
3). When assigning to a pointer, you should pay attention to the need not to release the assigned pointer.
4). It is best not to assign a pointer to dynamically allocated memory.
5). In C++, smart pointers should be given priority.

2. C and C++

1. What is the difference between C and C++?

  1. C++ is a superset of C;
  2. C is a structured language, and its focus is on algorithms and data structures. The first consideration in the design of C programs is how to process input (or environmental conditions) to obtain output (or realize process (transaction) control) through a process. For C++, the first consideration is how to construct an object model so that This model can fit the corresponding problem domain, so that the output or process (transaction) control can be achieved by obtaining the state information of the object.

2. What is the difference between int fun() and int fun(void)?

What is being examined here is the default type mechanism in c.

  • In c, int fun() will be interpreted as the return value of int (even if there is no int before, it is the same, but in c++, if there is no return type, an error will be reported), the input type and number are not limited, and int fun(void) Then restrict the input type to a void.
  • In C++, both cases will be interpreted as returning int type and entering void type.

3. What is the purpose of const

  1. Define read-only variables, or constants (refer to the next item for the difference between read-only variables and constants);
  2. Modify the parameters of the function and the return value of the function;
  3. The definition body of the modified function. The function here is the member function of the class. The member function modified by const means that the value of the member variable cannot be modified, so the const member function can only call the const member function;
  4. Read-only object. Read-only objects can only call const member functions.

4. Can const be used in C to define real constants? What about const in C++?

Not in c. The const in c is only limited from the compilation level. Assignment operations to const variables are not allowed. They are invalid at runtime, so they are not real constants (for example, the value of const variables can be modified through pointers), but c++ There is a difference between C++ and C++ will add const constants to the symbol table when compiling. Later (still at compile time) this variable will be looked up from the symbol table, so it is impossible to modify the const variable in C++ .

supplement:

  1. The local const constant in c is stored in the stack space, and the global const constant is stored in the read-only storage area, so the global const constant cannot be modified. It is a read-only variable.
  2. What needs to be explained here is that the constant is not just unmodifiable, but relative to the variable, its value has been determined at compile time, not at runtime.
  3. There is a difference between const and macro definitions in c++. Macros are directly replaced by text during the pre-compilation period, while const occurs during the compilation period and can be type checked and scope checked.
  4. Only enum can realize real constants in C language.
  5. In C++, only const constants initialized with literals will be added to the symbol table, and const constants initialized with variables are still only read-only variables.
  6. The const member in c++ is a read-only variable, and the value of the const member can be modified through the pointer. In addition, the const member variable can only be initialized in the initialization list.

5. Comparison of macros and inline functions?

  1. First of all, the macro is a preprocessing function introduced in C;
  2. Inline function is a new keyword quoted in C++; it is recommended to use inline function to replace macro code fragments in C++;
  3. The inline function directly expands the function body to the place where the inline function is called, which reduces the process of parameter pushing on the stack, jumping, and returning;
  4. Since inlining occurs in the compilation stage, compared with macros, inlining has parameter checking and return value checking, so it is safer to use;
  5. It should be noted that inline will request inline at compile time, but whether inline is determined by compile time (of course, you can force the use of inline by setting the compiler);
  6. Since inlining is an optimization method, in some cases, even if there is no explicit statement inlining, such as a method defined in a class, the compiler may use it as an inline function.
  7. Inline functions should not be too complicated. Initially, C++ limits cannot have any form of loops, cannot have too many conditional judgments, cannot perform address operations on functions, etc., but nowadays compilers have almost no restrictions and can basically achieve inlining .

6. With malloc/free in C++, why do I need new/delete?

  1. malloc and free are standard library functions of C++/C language, and new/delete are C++ operators. They can be used to apply for dynamic memory and release memory.
  2. For objects of non-internal data types, malloc/free alone cannot meet the requirements of dynamic objects. The object must automatically execute the constructor when it is created, and the object must automatically execute the destructor before it dies.
    Since malloc/free is a library function rather than an operator, it is not within the control of the compiler, and the task of executing the constructor and destructor cannot be imposed on malloc/free. Therefore, the C++ language needs an operator new that can complete dynamic memory allocation and initialization, and an operator delete that can complete cleanup and release of memory. Note that new/delete is not a library function.

Finally, add a digression, new can be initialized when applying for memory (the following code), but malloc is not allowed. In addition, because malloc is a library function and requires corresponding library support, some simple platforms may not support it, but new does not have this problem, because new is an operator that comes with the C++ language.

7. Coercion in C and C++?

In C, the target type (enclosed in parentheses) is added directly in front of the variable or expression to perform the conversion. It is a trick to go around the world and the operation is simple. However, because it is too direct and lacks checks, it is prone to errors that cannot be checked by compilation. , And manual inspection is extremely difficult to find; and C++ introduces the following four conversions:

  1. static_cast
    a. Used for conversion between basic types
    b. Cannot be used for conversion between basic type pointers
    c. Used for conversion between inherited class objects and conversion between class pointers
  2. dynamic_cast
    a. Used for conversion between class pointers with inheritance relationship
    b. Used for conversion between class pointers with cross relationship
    c. Has the function of type checking
    d. Needs the support of virtual functions
  3. reinterpret_cast
    a. Used for type conversion between pointers
    b. Used for type conversion between integers and pointers
  4. const_cast
    a. Used to remove the const attribute of the variable
    b. The target type of the conversion must be a pointer or reference

In C++, ordinary types can be converted to class types through the type conversion constructor. Can classes be converted to ordinary types? The answer is yes. However, type conversion functions are generally not used in engineering applications, because implicit calling of type conversion functions cannot be suppressed (type conversion constructors can be implicitly called through explicit), and implicit calls are often the source of bugs. The alternative way in actual engineering is to define a common function, and achieve the purpose of type conversion through explicit call.

8. What is the use of static

  1. Static (local/global) variables
  2. Static function
  3. Static data members of the class
  4. Class static member function

9. What are the characteristics of static member variables and static member functions of a class?

Static member variable

  1. Static member variables need to be declared within the class (add static), and initialized outside the class (not add static), as shown in the following example;
  2. Static member variables are allocated storage space separately outside the class and are located in the global data area. Therefore, the life cycle of static member variables does not depend on an object of the class, but objects of all classes share static member variables;
  3. You can directly access public static member variables through the object name;
  4. You can directly call public static member variables through the class name, that is, you do not need to go through the object, which is not available in ordinary member variables.
class example{
    
    
private:
static int m_int; //static成员变量
};

int example::m_int = 0; //没有static

cout<<example::m_int; //可以直接通过类名调用静态成员变量

Static member function

  1. Static member functions are shared by the class;
  2. Static member functions can access static member variables, but cannot directly access ordinary member variables (access through objects); note that ordinary member functions can access both ordinary member variables and static member variables;
  3. You can directly access public static member functions through the object name;
  4. The public static member function can be called directly by the class name, that is, the object does not need to be passed, which is not available in ordinary member functions.
class example{
    
    
private:
static int m_int_s; //static成员变量
int m_int;
static int getI() //静态成员函数在普通成员函数前加static即可
{
    
    
  return m_int_s; //如果返回m_int则报错,但是可以return d.m_int是合法的
}
};

cout<<example::getI(); //可以直接通过类名调用静态成员变量

10. When calling a function compiled by the C compiler in a C++ program, why add extern "C"?

C++ language supports function overloading. C language does not support function overloading. The name of the function in the library after being compiled by the C++ compiler is different from that of C language. Suppose a certain function prototype is:

 void foo(int x, int y);

The name of the function in the library after being compiled by the C compiler is _foo, and the C++ compiler will generate a name like: _foo_int_int. In order to solve this kind of name matching problem, C++ provides the C link exchange designated symbol extern "C".

11. What is the use of ifndef/define/endif in the header file? What is the difference between the usage and program once?

Same point:

Their role is to prevent header files from being repeatedly included.

difference:

  1. ifndef is supported by the language itself, but program once is generally supported by the compiler, that is, there may be situations where the compiler does not support it (mainly older compilers).
  2. Generally, ifndef is slower than program once in running speed, especially in large projects, the difference will be more obvious, so more and more compilers start to support program once.
  3. ifndef acts on a certain section of code that is included (between define and endif), while program once is for the file containing the statement, which is why program once is faster.
  4. If you use ifndef to include a certain macro definition, when the macro name appears "crash", it may appear that the macro is not defined in the program (the feature needs to be paid attention to when writing large programs, because there are many programmers at the same time. write the code). On the contrary, because program once refers to the entire file, there is no macro name "collision", but if a header file is copied multiple times, program once cannot guarantee that it will not be included multiple times, because program once is a physical judgment The same header file, not the content.

3. Arrays, pointers & references

1. What is the difference between pointer and reference?

Same point:

  1. It is the concept of address;
  2. All "point to" a piece of memory. The pointer points to a block of memory, and its content is the address of the pointed memory; and the reference is an alias for a block of memory;
  3. References are actually implemented internally by means of pointers. In some cases, references can replace pointers, for example, as function parameters.

difference:

  1. A pointer is an entity, and a reference (it seems very important) is only an alias;
  2. References can only be initialized once at the time of definition and are immutable afterwards; pointers are variable; references "from one to the end", pointers can "change differently";
  3. References cannot be null, pointers can be null;
  4. "Sizeof reference" gets the size of the pointed variable (object), and "sizeof pointer" gets the size of the pointer itself;
  5. The self-increment (++) operation meaning of pointer and reference is different;
  6. References are type-safe, but pointers are not (references have more type checking than pointers)
  7. Citations are more readable and useful.

2. Do references take up memory space?

Taking the address of the reference in the following code is actually the address of the memory space corresponding to the taken reference. This phenomenon makes people feel that the citation is not an entity. But the reference takes up memory space, and the memory it occupies is the same as the pointer, because the internal implementation of the reference is done through the pointer.

比如 Type& name; <===> Type* const name。

int main(void)
{
    
    
        int a = 8;
        const int &b = a;
        int *p = &a;
        *p = 0;
        cout<<a; //output 0
    return 0;
}

3. Ternary Operator

In C, the result of the ternary operator (?:) can only be used as an rvalue. For example, the following method will report an error under the C compiler, but it can be passed in C++. This progress is achieved through references, because the return result of the following ternary operator is a reference, and then assignment to the reference is allowed.

int main(void)
{
    
    
        int a = 8;
        int b = 6;
        (a>b ? a : b) = 88;
        cout<<a; //output 88
    return 0;
}

Four. C++ features

1. What is object-oriented (OOP)? The meaning of object-oriented?

  • Object Oriented Programming, Object Oriented Programming, is a method and idea to understand and abstract the real world, and an idea to deal with problems by transforming requirement elements into objects. The core idea is data abstraction, inheritance and dynamic binding (polymorphism) .
  • The significance of object-oriented is to introduce the habitual way of thinking in daily life into the program design; intuitively map the concepts in the requirements to the solution; build a reusable software system centered on modules; improve the maintainability of software products And scalability.

2. Explain encapsulation, inheritance and polymorphism?

Package:

  • Encapsulation is the first step to realize object-oriented programming. Encapsulation is to gather data or functions in individual units (we call them classes).
  • The meaning of encapsulation is to protect or prevent code (data) from being unintentionally destroyed by us.

inherit:

Inheritance mainly realizes the reuse of code and saves development time. The child class can inherit some things from the parent class.

  • a. Public inheritance (public)
    The characteristic of public inheritance is that when the public members and protected members of the base class are used as members of the derived class, they remain in their original state, while the private members of the base class are still private and cannot be derived by this Accessed by subclasses of the class.
  • b. Private inheritance (private)
    The characteristic of private inheritance is that the public members and protected members of the base class are both private members of the derived class and cannot be accessed by the subclasses of this derived class.
  • c. Protected inheritance (protected)
    The characteristic of protected inheritance is that all public members and protected members of the base class become protected members of the derived class and can only be accessed by its derived class member functions or friends. The private members of the base class remain It is private.

Polymorphism:

  • The polymorphism of the function is also called the overloading of the function. As long as one of the number, type and arrangement order of the function parameters is different, and the same function name, it is called the polymorphism of the function.
  • In a class, polymorphism is a variety of forms in which base types and derived types can be used interchangeably in many cases. Rely on dynamic binding mechanism.
  • Dynamic binding is not used by default in C++ (the default is static binding, not dynamic binding). To trigger dynamic binding, two conditions must be met:
  1. The formal parameter of the interface function must be a reference type or a pointer type
  2. Dynamic execution functions (member functions of object parameters rather than interface functions) must be declared as virtual member functions.

3. When is the default constructor (parameterless constructor) generated? When is the default copy constructor generated? What is a deep copy? What is a shallow copy? What kind of copy is the default copy constructor? When to use deep copy?

  1. When there is no constructor, the compiler will automatically generate a default constructor, that is, a parameterless constructor; when the class does not have a copy constructor, it will generate a default copy constructor.
  2. Deep copy refers to the same logical state of the object after copying, while shallow copy refers to the same physical state of the object after copying; the default copy constructor belongs to shallow copy.
  3. When a member in the system refers to a resource in the system, a deep copy is required. For example, it points to the dynamic memory space, opens the file in the external storage, or uses the network interface in the system. If deep copying is not performed, such as dynamic memory space, the problem of multiple releases may occur. The principle of whether you need to define a copy constructor is whether or not a member of the class calls system resources. If you define a copy constructor, you must define a deep copy, otherwise it is meaningless.

4. What is the execution order of constructor and destructor?

Constructor execution order

1). First call the constructor of the parent class;
2). Call the constructor of the member variable;
3). Call the constructor of the class itself.

Destructor

For stack objects or global objects, the calling sequence is just the opposite of the calling sequence of the constructor, that is, the post-construction is first destructed. For heap objects, the order of destruction is related to the order of delete.

Reference:
https://blog.csdn.net/kuweicai/article/details/82779648#t9

Guess you like

Origin blog.csdn.net/QLeelq/article/details/113615314