In-depth description of const

Source: Internet
Author: User
The const modifier can convert an object to a constant object. What does it mean? That is to say, the value of the variable modified using const cannot be modified at any position of the program, just like a constant. A good program has a very high utilization frequency of Const. It can ensure program security and improve program portability. 1. Replace defineconst # define d_int 100 # define d_long 100.29 use constconst int d_int = 100; const d_int = 100; // If the int type is defined, the int type can be omitted. const long d_long = 100.29; const Int & A = 100; const replaces define. Although it increases the allocation space, it ensures type security. in the C standard, the data defined by const is equivalent to the global data, and C ++ depends on the declared position. why does it increase the space, because define pre-compilation will replace all the above d_int with 100, and then 100 will be compiled into the code and stored in the code area; while const generates a constant d_int, in the program, d_int is compiled, But it points to a constant 100,100, which also exists in the Code zone. Therefore, a space is required more than define. 2. Const definition General constants generally refer to constants of simple types. In this case, const can be placed before or after the type specifiers. Int const int_a = 100; const int int_a = 100; // both define a constant array for the const and can be placed before and after the type specifier. The array should be initialized at the same time as the definition, such as: int const int_array [5] = {0, 1, 2, 3, 4}; 3. Const defines that a constant object is an object constant, the definition format is as follows: <Class Name> const <Object Name> const <type> <Object Name> const defines constant objects and initializes them only after initialization, objects cannot be changed. 4. Const defines the pointer const defines the pointer, which has different meanings with different positions. The definition of const on the left or right is different, but on the left of *, there is no difference between the definition on the left and the right of the type specifier. Const char * prt_1 = stringprt1; char const * prt_1 = stringprt1; the two have the same meaning. The const-modified Pointer Points to the variable, and prt_1 must point to the constant, that is, prt_1 can be changed, but the variables it points to cannot be changed. That is: prt_1 = stringprt2; // valid * prt_1 = "string"; // invalid char * const prt_2 = stringprt1; if the const is on the right side, it modifies the pointer direction, and prt_2 is a constant pointer. Therefore, the orientation of prt_2 cannot be changed, but it can be changed. Prt_2 = stringprt2; // invalid * prt_2 = "string"; // valid 5. The reference defined by const is a constant reference. That is, the object to which the reference is directed cannot be updated. The format is as follows: const double & D; constant pointer and common reference, often used for function parameters. Such parameters can be called common parameters. This method has two advantages: first, using a pointer or reference will not increase extra space and improve the program running efficiency. Second, you can avoid updating the original parameter values. Int int_1 = 10; void print (const Int & I) {cout <I <Endl;} First, use int I as the parameter if none of them are used, during the call, the program allocates a space in the memory to store this parameter. The stored parameter is a copy of the original value int_1. When the program runs, this parameter is released in the memory. This parameter exists in the stack. Therefore, it will reduce the efficiency. If & is used, the parameter is a reference. At this time, the parameter I in the print function is equivalent to an alias of the original value int_1. Although there is no copy, it improves the efficiency and space utilization, however, there may be potential threats. For example, if you modify the I value in the print function, the corresponding int_1 change will be affected. If you use const &, this risk is avoided. In the function, you will not have the permission to modify I, but you can only use it. 6. Const modifies a function, void fun (const A * In) or void fun (const A & In). As mentioned above, the advantage of modifying parameters is that it can improve efficiency and space utilization while avoiding accidental modification of called parameters in functions. Note that calling a variable in a common parameter function does not change whether the variable is a constant. B. Modify the return value const A & fun () or const A * Fun (). When returning a reference or pointer, avoid using local variables in the function as the return value, this variable will be released after the function is run, and the reference or pointer will become a wild reference or a wild pointer, which is a programming taboo. 7. Modify an operation in a class or an attribute a. A function in a frequently-member function class is called an operation or a member function. A member function modified with const is called a frequently-member function. The modification format is as follows: <return value type> function name (<parameter table>) const {}. the common object mentioned in above 3 can only access the common member function B. A common member function cannot modify the data of an object, regardless of whether the other party is a constant or not. If it is modified, an error occurs during compilation. Note: There are two conditions for modifying a member for a common object: The member cannot be modified for a common object. However, if a member is modified with a mutable modifier during class definition, including regular objects, you can also modify this member, or use the const_cast conversion operator to cancel the constant attribute of a constant and then modify it. For details about mutalbe and const_cast usage, refer to msdn or Google. Common member functions are very useful and can increase security. Although you can say that the function is compiled by you, you can ensure that the function you write will not modify the object, but only use it, but you need to know, the program you write may be shown to others in the future, or someone else may modify your code. Using the const modified regular member function is equivalent to clearly telling others, my member function does not modify objects and tells others that this function cannot modify objects at will. Otherwise, a bug may occur. Similarly, use const whenever possible when you need to use Const. B. Regular data members whose const is used are regular data members. Regular data members must be initialized in the initialization list. Class A {public: A (int I); const int A; const int B; int C; static int D;} A: A (int I ): A (I), B (a) {c = a + B;} int A: D = 10; in this example,, B can only use initialization list initialization, while C can use other methods. In addition, it should be noted that static data members must be initialized directly using the preceding method. Because static is different from other data members, each object of other data members has an instantiated member, however, static members in the class share all the members of the class. Write a class that contains an operation. The return value of this operation is the number of times the class is instantiated. Modify the operation to include another operation. The return value of this operation is the number of objects in the current class.


Task:1. It is best to write a program in some areas that are not quite understandable. 2. I have not completed all the verification, so there may be errors. Please write your own program for verification. I have just verified 4th Regular pointers and found that I wrote an error, which is the opposite. Now I have changed it. Therefore, you can understand the details only after you write a program for verification. At the same time, two problems were unexpectedly discovered: first, if you set a const int I; and then use & I to get its address, the type of this address is const int *. Therefore, you can only use the const int * PRT = & I; if you use an int * const PRT = & I;, an error occurs. This is an accident. I hope you can also try programming to verify and discover more interesting places. My verification 4 programs (vc6): # include <iostream> using namespace STD; void main () {int temp; const int I1 = 10; int I2 = 20; int I3 = 30; const int * ptr_1 = & I1; // int * const ptr_2 = & I1; // error int * const ptr_2 = & I2; ptr_1 = & I2; ptr_2 = 30; cout <* ptr_1 <"|" <* ptr_2 <Endl; CIN> temp ;} After a hands-on experiment, if you think you understand Const Now, let's look at the next page:


Problem 1: const int ival = 1024; const int * P = & ival; const int * & ref1 = & ival; // invalid const int * & ref2 = P; // valid const int * const & ref3 = & ival; // valid * & what does it mean? Why is ref1 illegal, while ref3 legal? What is reference? Question 2: Since const defines a variable as a constant, can it be like this: const int n = 5; char C [N]; analyze the result. Problem 3: typedef char * pstr; char string [4] = "ABC"; const char * P1 = string; const pstr P2 = string; P1 ++; P2 ++; excuse me, there is an error above. Where is the error? Why? Question 4: char * P = "I'm hungry! "; P [0] = 'I'; is there any problem with this code? Question 5: Is char a [3] = "ABC" Legal? What are the risks of using it? Question 6: const char * Pcontent; const (char *) Pcontent; char * const Pcontent; describes the const situation of the Three. Question 7: run the following code: # include <iostream> using namespace STD; void main () {int temp; const int x = 4; int * Y = (int *) (& X); (* Y) = 9; cout <Y <Endl; cout <& x <Endl; cout <* Y <Endl; cout <x <Endl; cin> temp;} You will find that Y is the same as X address, but the value is different. Think about why? Can there be two numbers in the same address? Think about it for a long time. If you cannot figure it out, let's look at the answer later.


Answer 1: The reference is equivalent to an alias for the variable and a variable name. * & Refers to the reference to the pointer, that is, to alias a const int pointer because the reference is to alias the variable, and & ival is an address, not a variable, the number of records saved by this address is constant and cannot be updated, but this address cannot be updated. If the const int * & ref1 = & ival; // is invalid, it can be compiled, ref1 can modify the address saved by this constant, which is obviously impossible. Therefore, unless a const modifier is added before the reference, I will not modify the address of this reference to pass. Answer 2: in ansi c, this writing method is incorrect, because in the Standard C language, const defines a read-only variable. Although it cannot be modified, it is still a variable, the memory occupies space, and the data size must be defined by constants. But in VC, this method is correct. Answer 3: first, think of a problem, that is, the const variable also exists in the stack, not in the Code zone. In this case, the error occurs in P2 ++; const char m; in this formula, M is immutable and const char * PM can be introduced; * PM is immutable, but PM is changed. Similarly, in const newtype m;, M is not variable because pstr is a new data type. Answer 4: Different compilers may be different. In vc6, the compiler can pass, because there is no explicit const above to indicate that P cannot be modified, but an error will occur during running, because, "I'm hungry! "It is actually a String constant, Which is saved in the read-only memory zone after compilation. P is actually the header address of this string constant. Therefore, an error occurs if you try to modify the content of this read-only memory zone. Answer 5: In Standard C, this is legal, but its living environment is very small. It defines an array of 3 and is initialized as "ABC". Note, it does not have the usual string Terminator '/0', so this array only looks like a string in C language, but it is not actually, so all functions that process the string, for example, strcpy and printf cannot be used on this fake string. Answer 6: const char * Pcontent; // * Pcontent is const, Pcontent variable const (char *) Pcontent; // Pcontent is const, * Pcontent variable char * const Pcontent; // Pcontent is const, * Pcontent variable because (char *) has been taken as a whole, equivalent to const type Pcontent. Obviously Pcontent is const, * Pcontent variable answer 7: you can try it like this and you will find that cout <* (& X) <Endl; the value is 4 cout <* (int *) (& X) <Endl; at this point, the value of 9 indicates a problem. First, const int X is saved in a read-only memory area. Therefore, if the value of X is 4, it will not become, similar to the macro replacement defined by define. Second, when the address of X is modified with (int *), another address is opened in the memory, that is, the address displayed in the program, the value under this address can be changed. The value in the program is changed to 9, but the value of X remains unchanged. About Const There are more and more problems. If you are interested, you can go Google Or Csdn . We recommend that you Csdn Apply for an account. If you want to know something about programming or have any problems, it is a great place. There is also a task: Please write one Int Type node static linked list, but to create, insert nodes, delete nodes, query nodes, delete linked list and other functions.

 

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.