String Literals

前端 未结 3 872
走了就别回头了
走了就别回头了 2020-11-27 19:30

I have few doubts about string literals in c++.

char *strPtr =\"Hello\" ;
char strArray[] =\"Hello\";

Now strPtr and strArray are considere

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 19:50

    char *strPtr ="Hello" ;
    

    Defines strPtr a pointer to char pointing to a string literal "Hello" -- the effective type of this pointer is const char *. No modification allowed through strPtr to the pointee (invokes UB if you try to do so). This is a backward compatibility feature for older C code. This convention is deprecated in C++0x. See Annex C:

    Change: String literals made const The type of a string literal is changed from “array of char” to “array of const char.” [...]

    Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument.

    Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Simple syntactic transformation, because string literals can be converted to char*; (4.2). The most common cases are handled by a new but deprecated standard conversion:

    char* p = "abc"; // valid in C, deprecated in C++

    char* q = expr ? "abc" : "de"; // valid in C, invalid in C++

    How widely used: Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare.

    char strArray[] ="Hello";
    

    The declared type of strPtr is -- it is an array of characters of unspecified size containing the string Hello including the null terminator i.e. 6 characters. However, the initialization makes it a complete type and it's type is array of 6 characters. Modification via strPtr is okay.

    Where exactly do string literals are stored ?

    Implementation defined.

提交回复
热议问题