A bug in constant string usage and G ++ in C

Source: Internet
Author: User

Const char * is used to define a pointer to a constant string, usually in the form:

Const char * PTR = "hello ";

However, many careless friends may not notice the following definition:

Const char * ptr2 = "hello ";

PTR and ptr2 point to the same piece of memory, that is, defining const char * PTR = "hello" is not equal to creating a new constant string, but trying to return the access address of a constant string, if the constant string does not exist, create a constant string and return the address of the constant string. This is not all true.

Const char * is a pointer. It has nothing to do with the acquisition and creation of constant strings. The access and creation of constant strings are completed by "hello". That's right, it is a constant string "hello" accessed through "hello". You can get a pointer to "hello" anytime, anywhere, "Hello" is created when it is used for the first time, and "hello" is used later to access this address.

For example:

Static const char *
Change_to_string (INT change)
{
Change & = (ev_change_add | ev_change_del );
If (change = ev_change_add ){
Return "add ";
} Else if (change = ev_change_del ){
Return "Del ";
} Else if (change = 0 ){
Return "NONE ";
} Else {
Return "??? ";
}
}

Return A String constant in return mode, which can replace static variables of some functions.

G ++ bug

G ++ has a bug in processing the return value of the constant string type. The preceding example returns const char *, which is also a well-known safe String constant access method, but you can also define the return value type as char *. Yes, you can define it as char * and use a char * pointer to receive it, after breaking through the limit that const char * cannot be assigned to char *, You have done it, and your code is dangerous. When you modify the constant string, you will have the core.

This bug is worth trying, but you don't have.

A bug in constant string usage and G ++ in C

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.