原完整教程链接:6.8b C-style string symbolic constants
1.
/*
Rule: Feel free to use C-style string symbolic constants if you need
read-only strings in your program, but always make them const!
*/
int main()
{
const char *myName = "Alex"; // <-- C-style string symbolic constant
std::cout << myName;
return 0;
}
/*
EXPLANATION FOR ABOVE CODE:
What usually happens is that the compiler places the string
“Alex\0” into read-only memory somewhere, and then sets the
pointer to point to it. Multiple string literals with the same content
may point to the same location. Because this memory may be
read-only, and because making a change to a string literal may
impact other uses of that literal, best practice is to make sure the
string is const. Also, because strings declared this way are
persisted throughout the life of the program (they have static
duration rather than automatic duration like most other locally
defined literals), we don’t have to worry about scoping issues.
My personal understanding of ** const char *myName = "Alex"; **:
编译器把Alex\0放到一个只读的内存区,然后把这个内存区的地址赋值给myName。
也就是说,其实这个语句是省略掉了一个中间步骤的:它省略掉了放Alex\0这一步。
*/
2.
// Consider the following example:
int main()
{
int nArray[5] = { 9, 7, 5, 3, 1 };
char cArray[] = "Hello!";
const char *name = "Alex";
std::cout << nArray << '\n'; // nArray will decay to type int*
std::cout << cArray << '\n'; // cArray will decay to type char*
std::cout << name << '\n'; // name is already type char*
return 0;
}
/* On the author’s machine, this printed:
003AF738
Hello!
Alex
Why did the int array print an address, but the character arrays
printed strings?????
The answer is that std::cout makes some assumptions about your
intent. If you pass it a non-char pointer, it will simply print the
contents of that pointer (the address that the pointer is holding).
However, if you pass it an object of type char* or const char*, it
will assume you’re intending to print a string. Consequently,
instead of printing the pointer’s value, it will print the string being
pointed to instead!
*/