C and C ++ language learning Summary (Source:
Knowledge Structure:
1. If, for, switch, Goto
2. # define, const
3. CopyCode, Dynamically generated memory, composite expression, strcpy, memcpy, sizeof
4. function parameter transfer, memory allocation method, memory error performance, difference between malloc and new
5. Differences between class overloading, hiding and overwriting, extern, default value of function parameters, and differences between macro code and inline functions
6. Structure and structure order, defined by the string Function
Specific implementation:
1. If, for, switch, Goto
If:
How to Use the bool int float pointer char variable
Bool bparam;
Int iparam;
Float fparam;
Int * pparam;
Char cparam;
If (bparam), if (! Bparam );
If (iparam = 0), if (iparam! = 0 );
If (fparam> =-0.00001 & fparam <= 0.00001 );
If (pparam = NULL), if (pparam! = NULL );
If (cparam = '\ 0'), if (cparam! = '\ 0 ');
How to use if/else/Return
If (condition) can be equivalent to return (condition? X: Y );
{
Return X;
}
Else
{
Return y;
}
For:
Execution efficiency:
Int row, Col, sum;
Int A [100] [5];
For (ROW = 0; row <100; row ++) is less efficient than for (COL = 0; Col <5; Col ++)
{{
For (COL = 0; Col <5; Col ++) for (ROW = 0; row <100; row ++)
{{
Sum = sum + A [row] [col]; sum = sum + A [row] [col];
}}
}}
Int I;
For (I = 0; I <n; I ++) is less efficient than if (condition)
{{
If (condition) for (I = 0; I <n; I ++)
Dosomething ();
Else}
Dootherthing (); else
}{
For (I = 0; I <n; I ++)
Dootherthing ();
}
For (INT x = 0; x <= N-1; X ++) for (INT x = 0; x <n; X ++)
Switch:
Switch (variable)
{
Case value1 :...
Break;
Case value2 :...
Break;
Default :...
Break;
}
The data type of C in switch (c) can be int, Char, long, unsigned int, bool.
Variable must be an integer or a mandatory integer. Because char is actually an ascii code, you can also.
C cannot be double, float, char *.
Goto:
Goto is mainly used
{...
{...
{....
Goto error;
}
}
}
Error:
...
2. # define, const
# Difference between define and const
1. # define C Language
Const C Language C ++
Const constants have data types. The Compiler performs type security checks, while # define does not have data types,
Const constants can be debugged, but macro constants cannot be debugged.
2. Usage of const
Define const float Pi = 3.1415926 globally
Define in class
Class
{...
A (INT size );
Const int size;
};
A: A (INT size): size (size)
{
...
}
Definition of parameters and functions (const can only modify input parameters, but cannot modify output parameters)
Const int x = 1; indicates that the value of X is 1, inProgramCannot be changed;
Const int * X; indicates that the content pointed to by X represents cannot be changed;
Int const * X; it means the same as const int * X;
Int * const X; indicates that the address represented by X cannot be changed;
When the parameter is input, void func (const int I), void func (const Int & I), can be void func (int I)
Because the input parameter uses "value transfer" (const int I), because the function will automatically generate a temporary variable for copying this parameter, the input parameter does not need to be protected, so do not add const modification;
The reason for not using const Int & I is that the internal data type parameters do not have a structure or structure process, and replication is fast, the efficiency of "value transfer" and "reference transfer" is almost the same.
When the parameter is input, it does not need to be void func (const A), void func (A), it can be void func (A & A) or void func (const A &)
No const A. The reason for a A is that the function is less efficient, because a temporary object of type A will be generated in the function body for copying parameter, the construction, replication, and destructor of temporary objects all consume time.
It is best to use const A & A because a and a in a & A can be changed. The advantage of A & A and const A & A is that they do not produce temporary objects and are highly efficient;
Const a func (const A & A) const benefits
The first const indicates that an internal object is returned and cannot be modified.
Const a func (...)
{...}
Const A = func (...); // it cannot be a = func (...);
The second const indicates that the input parameter is passed by reference, and no temporary object is generated in the function, and this object cannot be modified internally.
The third const indicates that the data members involved in the function cannot be modified.
Class Stack
{
Int m_num;
Int getcount (void) const;
Int POP (void );
}
Int Stack: getcount (void) const
{
M_num ++; // compilation error. An attempt is made to modify the data member m_num;
Pop (); // compilation error in an attempt to call a non-const Function
}
3. file copy code
# Include <stdio. h>
Int main (INT argc, char * argv [])
{
Printf ("Hello world! \ N ");
File * in;
File * out;
In = fopen ("D: \ 1.txt"," rb ");
Out = fopen ("D: \ 2.txt"," WB ");
Char CH = fgetc (in );
While (! Feof (in ))
{
Fputc (CH, out );
Ch = fgetc (in );
}
Fclose (in );
Fclose (out );
Return 0;
}
Dynamically generated Memory code
------------------------------------------
Correct code:
Void getmemory (char ** P, int num)
{
* P = (char *) malloc (sizeof (char) * num );
}
Char * getmemory2 (INT num)
{
Char * P = (char *) malloc (sizeof (char) * num );
Return P;
}
------------------------------------------
Error code:
Void getmemory3 (char * P, int num)
{
P = (char *) malloc (sizeof (char) * num );
}
------------------------------------------
Void test (void)
{
Char * STR = NULL;
Getmemory (& STR, 100); // note that the parameter is & STR, not Str
Strcpy (STR, "hello ");
Cout <STR <Endl;
Free (STR );
STR = NULL;
STR = getmemory2 (100 );
Strcpy (STR, "hello ");
Cout <STR <Endl;
Free (STR );
STR = NULL;
Getmemory3 (STR, 100); // STR is still null
Strcpy (STR, "hello"); // running error
Cout <STR <Endl; // running error
Free (STR); // running error
}
Strcpy code
Char * strcpy (char * strdest, const char * strsrc)
{
If (strdest = NULL | strsrc = NULL) return NULL;
Char * pstr = strdest;
While (* strdest ++ = * strsrc ++ )! = '\ 0)
NULL;
Return pstr;
}
Compound expression
D = (A = B + C) + R;
This expression evaluates both A and D. It should be split into two independent statements:
A = B + C;
D = a + R;
If (A <B <c) // A <B <C is a mathematical expression rather than a program expression
Does not indicate
If (A <B) & (B <C ))
It is rather confusing.
If (A <B) <C)
Memcpy code
Void * memcpy (char * strdest, const char * strsrc, size_t size)
{
If (strdest = NULL | strsrc = NULL) return NULL;
If (size <= 0) return NULL;
Char * pstr = strdest;
While (size --> 0)
* Strdest ++ = * strsrc ++;
Return pstr;
}
Sizeof:
I. Basic data types in 32-bit operating systems
Type Byte Length
Char 1
Short 2
Short int 2
Signed short 2
Unsigned short 2
Int 4
Long int 4
Signed int 4
Unsigned int (unsigned) 4
Long 4
Unsigned long 4
Float 4
Double 8
Void * 4 (all pointer types have the same length) (char *, int *, float *, double *)
Enum 4
Ii. In a 32-bit operating system, the size in the definition or function
Char A [] = "hello ";
Char B [100];
Char * P =;
Type Byte Length
Sizeof (a) 6
Sizeof (B) 100
Sizeof (p) 4
Void func (char a [1, 100])
{
Sizeof (a); // 4
}
# Pragma pack (1)
Struct
{
Int I;
Char J;
};
Sizeof (a) // 5
# Pragma pack (1)
Struct
{
Int o;
Int J;
Union
{
Int I [10], J, K;
};
};
Sizeof (a) // 48
# Pragma pack (1)
Struct
{
Enum day {monring, moon, aftermoon };
};
Sizeof (a) // 1
Sizeof (A: Day) // 4
4. function parameter transfer
In C ++, function parameters and return values are transmitted in three ways: value transfer, pointer transfer, and reference transfer.
"Value transfer" example program. Because X in the func1 function is a copy of the external variable N,
Changing the value of X does not affect N, so the value of N is still 0.
Void func1 (int x)
{
X = x + 10;
}
...
Int n = 0;
Func1 (N );
Cout <"n =" <n <Endl; // n = 0
Example program for "pointer passing". Since X in the func2 function is directed to the external variable N
Needle, changing the content of this pointer will lead to the change of N value, so the value of N becomes 10.
Void func2 (int * X)
{
(* X) = (* x) + 10;
}
...
Int n = 0;
Func2 (& N );
Cout <"n =" <n <Endl; // n = 10
Example program of "reference transfer". Since X in the func3 function is referenced by the external variable n, x
It is the same as N. Changing X is equal to changing N, so the value of N is 10.
Void func3 (Int & X)
{
X = x + 10;
}
...
Int n = 0;
Func3 (N );
Cout <"n =" <n <Endl; // n = 10
Memory Allocation Method
Allocation mode variable type allocation features
Global variables are allocated to the static storage area. The static variables are allocated when the program is compiled.
The local variable stack memory allocation operation in the stack allocation function is embedded in the instruction set of the processor. The efficiency is very high, but the allocated memory capacity is limited.
Heap allocation (also known as dynamic memory allocation) New, malloc allocation use malloc or new to apply for any amount of memory, the programmer is responsible for when to use free or delete to release the memory.
Memory Error
The memory allocation fails, but it is used.
Although the memory allocation is successful, it is referenced before initialization.
The memory allocation is successful and initialized, but the operation is beyond the memory boundary. for example, when an array is used, the subscript "more than 1" or "Less 1" is often performed. especially in for loop statements, the number of loops is easy to make a mistake, resulting in array operations out of bounds.
I forgot to release the memory, causing memory leakage.
But the memory is used.
The Return Statement of the function is incorrect. Do not return "Pointer" or "Reference" pointing to "stack memory" because the function body is automatically destroyed when it ends.
The object calling relationship in the program is too complex, so it is difficult to figure out whether an object has released the memory. At this time, we should re-design the data structure to fundamentally solve the chaos of Object Management.
After the memory is released using free or delete, the pointer is not set to null, resulting in "Wild Pointer ".
Difference between malloc and new
Malloc and free are standard library functions in C ++/C, and new/delete are c ++ operators. They can be used to apply for dynamic memory and release memory.
For non-Internal data objects, 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. because 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. 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.
5. Differences between class overloading, hiding, and overwriting
Features of member functions being overloaded:
(1) the same range (in the same class );
(2) The function name is the same;
(3) parameters are different;
(4) virtual keywords are optional.
Override refers to the function of a derived class that overwrites the base class function. The features are as follows:
(1) different scopes (located in the derived class and the base class respectively );
(2) The function name is the same;
(3) The parameters are the same;
(4) basic functions must have virtual keywords.
# Include <iostream. h>
Class base
{
Public:
Void F (int x) {cout <"base: F (INT)" <x <Endl ;}
Void F (float X) {cout <"base: F (float)" <x <Endl ;}
Virtual void g (void) {cout <"base: G (void)" <Endl ;}
Void H (float X) {cout <"base: H (float)" <x <Endl ;}
Void K (float X) {cout <"base: K (float)" <x <Endl ;}
};
Class derived: public Base
{
Public:
Virtual void g (void) {cout <"derived: G (void)" <Endl ;}
Void H (int x) {cout <"derived: H (INT)" <x <Endl ;}
Void K (float X) {cout <"derived: K (float)" <x <Endl ;}
};
Void main (void)
{
Derived D;
Base * pb = & D;
Derived * Pd = & D;
Pb-> F (42); // base: F (INT) 42 // heavy load
Pb-> F (3.14f); // base: F (float) 3.14 // heavy load
Pb-> G (); // derived: G (void) // Overwrite
Pd-> G (); // derived: G (void) // Overwrite
Pb-> H (3.14f) // base: H (float) 3.14 // hide
Pd-> H (3.14f) // derived: H (INT) 3 // hide
Pb-> K (3.14f) // base: K (float) 3.14 // hide
Pd-> K (3.14f) // derived: K (float) 3.14 // hide
}
Extern Problems
What if a C ++ program needs to call a compiled C function?
Assume that the declaration of a C function is as follows:
Void Foo (int x, int y );
After the function is compiled by the C compiler, its name in the library is _ Foo, while the C ++ compiler generates names such as _ foo_int_int to support function overloading and secure type connection. c ++ programs cannot directly call C functions because their compiled names are different. c ++ provides a C connection to exchange the specified symbol extern "c" to solve this problem. for example:
Extern "C"
{
Void Foo (int x, int y );
... // Other functions
}
Or write it
Extern "C"
{
# Include "myheader. H"
... // Other C header files
}
This tells C ++ to compile the interpreter. Function foo is a C connection, you should find the name _ Foo in the library instead of _ foo_int_int.c ++. The Compiler developer has already processed the header file of the C standard library with extern "C, so we can use # include to directly reference these header files.
Default Value of function parameters
Correct method:
Void Foo (INT x = 0, int y = 0); // correct. The default value is displayed in the function declaration.
Void Foo (int x, int y)
{
...
}
Error Method:
Void Foo (INT x = 0, int y = 0) // error. The default value appears in the definition body of the function.
{
...
}
Correct method:
Void Foo (int x, int y = 0, int z = 0 );
Error Method:
Void Foo (INT x = 0, int y, int z = 0 );
Differences between macro code and inline functions
Language Support relationships:
C macro code
C ++ macro code inline functions
Macro code itself is not a function, but it is used as a function. the pre-processor replaces the function call by copying macro code, saving the process of parameter pressure stack, generating call calls, return parameters, and executing return in the assembly language, thus improving the speed. the biggest disadvantage of using macro code is that it is prone to errors. The Preprocessor often produces unexpected marginal effects when copying macro code.
For any inline function, the compiler puts the declaration of the function (including the name, parameter type, and return value type) in the symbol table ). if the compiler does not find any error in the inline function, the code of the function is also placed in the symbol table. when calling an inline function, the compiler first checks whether the call is correct (for a type security check or automatic type conversion, of course, all functions are the same ). if correct, the code of the inline function replaces the function call directly, saving the overhead of the function call. this process is significantly different from preprocessing because the pre-processor cannot perform type security checks or perform automatic type conversion. if the inline function is a member function, the object address (this) will be placed in a suitable place, which is not implemented by the Preprocessor.
Inline Function usage:
The keyword inline must be put together with the function definition body to make the function inline. It does not work unless you put inline before the function declaration.
Correct usage:
Void Foo (int x, int y );
Inline void Foo (int x, int y) // put inline together with the function definition body
{
...
}
Incorrect usage:
Inline void Foo (int x, int y); // inline is only put together with the function declaration
Void Foo (int x, int y)
{
...
}
6. Structure and structure order
The construction starts from the root of the class hierarchy. In each layer, the base class constructor is called first, and then the member object constructor is called. the structure is executed strictly in the order opposite to the structure. This order is unique. Otherwise, the compiler cannot automatically execute the structure process.
String Function Definition
Class string
{
Public:
String (const char * STR = NULL); // common Constructor
String (const string & other); // copy the constructor
~ String (void); // destructor
String & operate = (const string & other); // value assignment function
PRIVATE:
Char * m_data; // used to save strings
};
// String destructor
String ::~ String (void)
{
Delete [] m_data; // because m_data is an internal data type, you can also write it as delete m_data;
}
// String Constructor
String: string (const char * Str)
{
If (STR = NULL)
{
M_data = new char [1]; // It is better if null can be added
* M_data = '\ 0 ';
}
Else
{
Int length = strlen (STR );
M_data = new char [Length + 1]; // It is better if null can be added.
Strcpy (m_data, STR );
}
}
// Copy the constructor
String: string (const string & other)
{
Int length = strlen (other. m_data );
M_data = new char [Length + 1]; // It is better if null can be added.
Strcpy (m_data, other. m_data );
}
// Value assignment function
String & string: operate = (const string & other)
{
// (1) Check the auto-assigned Value
If (this = & other)
Return * this;
// (2) release the original memory resource
Delete [] m_data;
// (3) allocate new memory resources and copy the content
Int length = strlen (other. m_data );
M_data = new char [Length + 1]; // It is better if null can be added.
Strcpy (m_data, other. m_data );
// (4) return the reference of this object
Return * this;
}