Question 1: What is the difference between const and # define?
C ++ can use const to define constants or # define to define constants. However, the former has more features than the latter:
1. Const constants have data types, while macro constants do not. The compiler can perform a type security check on const, but only replace the latter with characters without a type security check. In addition, unexpected errors (marginal effect) may occur during character replacement ).
2. Some integrated debugging tools can debug const constants, but cannot debug macro constants. In the C ++ program, only the const constant is used, but not the macro constant. That is, the const constant completely replaces the macro constant.
3. Different compiler Processing Methods
The define macro is expanded in the preprocessing phase.
Const constants are used in the compilation and running phase.
4. Different Storage Methods
The define macro is just an extension. If it is used in many places, it is expanded as many times without allocating memory.
Const constants are allocated in memory (either in heap or stack ).
Question 2: # some frequently asked questions about define.
1. What is the output of the following code?
# Define sqr (x) (x * X)
Main ()
{
Int A, B = 3;
A = sqr (B + 2 );
Printf ("/n % d", );
}
A = B + 2 * B + 2 = 3 + 2*3 + 2 = 11
If you use # define sqr (x) * (x), the output is 25.
2. Use the preprocessing command # define to declare a constant to indicate the number of seconds in a year (ignore the leap year problem)
# Define seconds_per_year (60*60*24*365) UL
The interviewer wants to see the following:
1) # basic knowledge of define syntax (for example, it cannot end with a semicolon, use of parentheses, and so on)
2) knowing that the pre-processor will calculate the value of a constant expression for you, therefore, it is clearer without a cost to directly write how much seconds you have in a year instead of calculating the actual value.
3) realize that this expression will overflow the integer number of a 16-bit machine-so the long integer sign L is used to tell the compiler that this constant is the long integer number.
4) if you use ul (representing an unsigned long integer) in your expression, you have a good starting point. Remember, the first impression is very important.
3. Write a "standard" macro min, which inputs two parameters and returns a smaller one.
# Define min (A, B) (a) <= (B )? (A): (B ))
This test is intended for the following purposes:
1) ID # basic knowledge of define application in macros. This is important. Before the inline operator becomes part of standard C, macros are the only way to easily generate embedded code. For embedded systems, in order to achieve the required performance, embedded code is often a required method.
2) knowledge of triple-condition operators. The reason for the existence of this operator in C language is that it enables the compiler to produce code that is more optimized than if-then-else. It is important to understand this usage.
3) Be careful to enclose parameters in brackets in macros.
Question 3: const usage and benefits.
Const usage summary:
1. Basic statement:
Const int max = 100; // standard const variable declaration and initialization, because the default internal connection must be initialized, its scope is this file, after checking the type, the compiler replaces it with 100 at compilation.
Const int MAX [] = {1, 2, 3, 4 };
Struct s {int A, B ;};
Const s [] = {(1, 2), (3.4)}; // the above two types are constant sets, and the compiler allocates memory for them, therefore, you cannot use the value during compilation, for example, int buffer [Max [2]. Such a compiler reports that constant expressions cannot be found.
2. Modify the pointer
Const int;
Int const;
Const int *;
Int * const;
Int const * a const;
The first two functions are the same. Declare a as a common integer. (But such writing is obviously not allowed, because the variables defined by const must be initialized .) The third indicates that A is an integer pointer to a constant integer variable, that is, a can be modified, and a cannot be modified. The fourth is opposite to the third, that is, a is a constant integer pointer to an integer variable, that is, a cannot be modified, and a can be modified. The fifth is obviously that neither a nor a can be modified.
3. type check
Int max = 100;
Const int * P = & Max;
// Assign a non-const object to a pointer pointing to const, because sometimes we don't want to modify the value of the object from this pointer;
Const int max = 100;
Int * Pi = & Max; // an error is returned. You cannot assign a const object to a non-const pointer because the pointer may change the value pointing to the object.
Const int max = 100;
Int * PTR = const_cast <int *> (& MAX); // C ++ standard, C language: int * PTR = (int *) & Max;
// However, there is also a way to make this operation pass through the legal writing, the use of type forced conversion can change the const object through the pointer, but the test shows that even if this method is passed, the max value cannot be modified through * PTR.
4. For character Arrays
Statements such as char * name = "China" can be passed during compilation, but "China" is a constant character array, any operation that you want to modify can also be compiled but may cause runtime errors. If you want to modify the character array, you need to use the char name [] = "China"; format.
5. Modify function parameters
Const modifier is the most widely used function parameter. It indicates that the parameter value cannot be modified in the function body (including the value of the parameter itself or the value contained in the parameter ).
Void function (const int var); // The passed parameters cannot be changed in the function (meaningless, because var itself is a form parameter, even if VaR is changed in the function body, the original VaR value also remains unchanged)
Void function (const int * var); // The content indicated by the parameter pointer is constant immutable
Void function (int * const var); // The parameter pointer itself is a constant and immutable (also meaningless, because char * VaR is also a form parameter), because VaR is the address value at this time, in this case, * VaR is the real parameter and VaR is the form parameter. In this case, the * VaR value can still be modified in the function body, but the VaR address value remains unchanged, but the value pointed to by this address has changed.
The parameter is a reference. To increase efficiency and prevent modification.
When modifying referenced parameters:
Void function (const Class & var); // The referenced parameter cannot be changed in the function.
Void function (const type & var); // The referenced parameter is a constant in the function and cannot be changed.
6. Modify the function return value
The const modifier function does not actually return a lot of values. Its meaning is basically the same as that of the const modifier for common variables and pointers.
(1) const int fun1 () is meaningless because the return value of the parameter itself is a value.
(2) const int * fun2 ()
Const int * pvalue = fun2 ();
We can regard fun2 () as a variable, which is the method of 1. (1) mentioned above, that is, the pointer content is immutable.
(3) int * const fun3 ()
Int * const pvalue = fun2 ();
We can regard fun2 () as a variable, so it is the method of 1. (2) mentioned above, that is, the pointer itself is immutable.
7. Modify Class Object/Object Pointer/Object Reference
The const modifier Class Object indicates that the object is a constant object, and no member can be modified. The same is true for object pointers and object references.
Const modified object, any non-const member function of this object cannot be called, because any non-const member function will attempt to modify the member variable.
For example:
Class aaa
{
Void func1 ();
Void func2 () const;
}
Const AAA aobj;
Aobj. func1 (); ×
Aobj. func2 (); correct
Const AAA * aobj = new AAA ();
Aobj-> func1 (); ×
Aobj-> func2 (); correct
8. Modify the member variables of the class.
If a const modifies a member function of a class, the member function cannot modify any non-const member function of the class. It is generally written at the end of the function.
Class
{
...
Void function () const; // a regular member function. It does not change the object's member variables, nor can it call any non-const member functions in the class.
}
For const class objects, pointers, and references, only the const member functions of the class can be called. Therefore, the most important function of const member functions is to restrict the use of const objects.
Benefits of using const:
1) The function of the keyword const is to send very useful information to the person who reads your code. In fact, the purpose of declaring a parameter as a constant is to inform the user of the application of this parameter. If you spend a lot of time cleaning up the garbage left by others, you will soon learn to thank this excess information. (Of course, programmers who know how to use const seldom leave garbage for others to clean up .)
2) by attaching some information to the optimizer, using the keyword const may produce more compact code.
3) the rational use of the keyword const can enable the compiler to naturally protect those parameters that do not want to be changed, so as to prevent them from being accidentally modified by code. In short, this can reduce the occurrence of bugs.
Question 4: The const difference between C and C ++.
The introduction of constants was in the early C ++ version, when the standard C Specification was being developed. At that time, constants were included in C as a good idea. However, const in C means "a common variable that cannot be changed ". In C, it always occupies memory and its name is a global character. The C compiler cannot regard const as a constant during compilation. In C, if you write:
Const bufsize = 100;
Char Buf [bufsize];
Although it seems that a reasonable task has been done, this will produce a wrong result. Because bufsize occupies memory somewhere, the C compiler does not know its value during compilation. In C, you can choose to write as follows:
Const bufsize;
This statement is incorrect in C ++, and the c compiler uses it as a declaration. This statement is well known for memory allocation elsewhere. C const is an external connection by default, and C ++ is an internal connection by default. In this way, if you want to do the same thing in C ++, you must use extern to change the internal connection to an external connection:
Extern const bufsize;
This method can also be used in C. Using the qualifier const in C language is not very useful, even if you want to use a named value in a constant expression (which must be obtained during compilation), using the const is not very useful. C forces programmers to use # define in a Preprocessor.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/crescent_star/archive/2009/03/18/4001602.aspx