Starting from the statement char * P = "test"

Source: Internet
Author: User

Author: Chen Hao Source: programmers ithao123 sorting

 

 

I believe that people who have been using C/C ++ for many years will not be unfamiliar with the following string assignment statements.

Char * P = "test ";

At the same time, I believe that you have suffered a lot after using such statements? As long as you want to use the pointer P to change the content of the string, yourProgramYou will get an invalid memory operation. For example, the following statements:

P [0] ='s ';
Strcpy (P, "haoel ");

The reason is that char * P = "test"; this statement declares a pointer, which pointsGlobal const memory ZoneThe const memory zone won't be changed if you want to change it. Therefore, if you must write this memory, it is a very serious memory error. In addition, the reason for the bold "Global const memory zone" is to emphasize that, if you do not believe it, you can try the following sectionCodeTo see if the P1 and P2 addresses are the same.

Char * P1 = "anything ";
Char * P2 = "anything ";
Printf ("P1 = % x, P2 = % x \ n", P1, P2 );

I think this is a well-known question. Instead, the array should be used for initialization declaration. For example: Char STR [] = "Hello World"; if the C example in another book uses the const string to initialize the pointer, then you can tear up the book. If the book is a C ++ book, you should take the author and the press to court, because you should not tolerate such academic scammers. If a developer in your department still writes this code, if he is a C programmer, I think you can tell him if he doesn't take it as an example after hitting his ass, if he is a C ++ programmer, I think you can doubt whether he is qualified to be a C ++ programmer.

As for why do you ask me why I want to be so harsh on people who have learned C ++, it is because people who have learned C ++ know the power of the const keyword in C ++, you should also know that C ++ has great care and care for const. Almost all books about C ++ will mention Const. Therefore, if you don't know it as a C ++ programmer, you can't say it.

We know that the string caused by double quotation marks is const. Therefore, in the C ++ world, you should make the following statement to make it safer:

Const char * P = "test ";

In this way, when you modify the content of this string, the compiler will give you an error, resulting in your program compilation failure, and thus will not generate runtime memory errors.

The problem is, for a language with strict type requirements such as C ++, why does it not make an error when compiling a program such as char * P = "test, even no warning (G ++ or VC ++ 7 )? Is this his bug? I think this should be a backward compatibility with the old C. This is because in the world of C, there are too many such usages.

In C ++, for example, function parameters and exception capturing all have this problem, as shown below: (depending on the compiler, in GCC 3.4.3, the exception examples in the following example cannot be captured, but can be captured in VC ++ 6)

Func (char * P) {}// call the function func ("ABC") in this way ");

Try {thow "exception";} catch (char * P ){}

These are the crimes that the C ++ compiler can convert const char * To char * by default, which will undoubtedly be misleading to everyone. They even let people go unafraid and think they are on the right path. In this case,This backward compatible C ++ standard seems a bit confusing..

Fortunately, the C ++ Standards Committee has long recognized this point. This C ++ feature is defined as "deprecated feature", that is, "features not recommended ". This means that in the future, this feature will be removed from C ++, so your current program will not be compiled on the new C ++ compiler. For program portability, pay special attention to the "deprecated feature" in the code we write today ".

As far as I know, the "deprecated feature" column in C ++ is as follows (which may be inaccurate. please correct me) the following feature has been set by the C ++ Standards Committee to abolish featrue.

1. Implicit const conversion of strings.

Char * P = "test ";
W_char * PW = l "test ";

Converts a const string type to non-Const. Including pointers and arrays.

2. Concealed type declaration.

Func () {} // the implicit return type of the function is int static num; // the implicit return type of the variable is int

This feature can also be used in c89, but it is removed in c99 and C ++. (GCC 3.4 will give compilation errors for such declarations, and VC ++ 6.0 will regard this as a legal Program)

3. accumulate a Boolean variable.Bool isconn = false; isconn ++; // This operation changes isconn to true.

For now, almost all compilers accept this operation, but this usage is not recommended and will be canceled one day.4. Modify the access permissions of the parent class members.

Class B
{
Protected:
Int I;
};

Class D: Public B
{Public:
B: I; // This method is rarely seen.
};

For this syntax, the subclass re-exposes the Private Members of the parent class. This will bring about a lot of security issues. Currently, this feature can be compiled by all compilers (not even a warning ). However, this feature will also be abolished.

V. Static Declaration of the domain in the file

Static int I;
Static void func ()

It is said that this old feature in C will also be canceled in the future C ++ in order to implement its scope in this file.

ArticleThis should end. Before the end, let me share an interesting example of const with you (shown on the Internet)

Const int A = 1;
Int * P = const_cast <int *> (& );
* P = 2;
Cout <"Value A =" <A <Endl;
Cout <"value * P =" <* P <Endl;
Cout <"address a =" <& A <Endl;
Cout <"address P =" <p <Endl;

The output result of this Code is as follows:

Value A = 1
Value * P = 2
Address a = 0xbff1d48c
Address P = 0xbff1d48c

The addresses are the same. Why are the values different? Haha. This question seems to be too academic, but it is just a good example to let you know some usage and principles of C ++. You can consider the following aspects: 1) is const int A = 1 like a macro? Will it be optimized by the compiler? 2) It should have been wrong to modify the value of a const. This may be compatible with the old C. Will the compiler generate unknown behavior?

Therefore, this example also tells us that we should follow the const and non-const semantics in C ++. Anything that wants to destroy this semantics will bring us unknown results.

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.