字符串字面量类型不符预期,请问"hello"的实际类型是什么?
Type of String Literal
"hello" Explained Hey there! Let's break down the type of string literals like "hello" and touch on why you might be seeing unexpected zero values in your program.
First, the core answer you’re looking for:
- In C++, the string literal
"hello"has an actual type ofconst char[6]. The6accounts for the 5 characters in "hello" plus the mandatory null terminator\0that the compiler automatically appends to every string literal behind the scenes. - In C, the type is technically
char[6](noconstqualifier), but this is a holdover from older standards—string literals in C are still read-only, and modifying them will cause undefined behavior (crashes, garbage output, etc.). Modern C compilers will warn you if you try to assign a string literal to a non-const char*.
Common Pitfalls That Might Cause Zero/Unexpected Values
If your program is returning zero instead of what you expected, it’s likely tied to how the string literal is being used:
- Implicit Array-to-Pointer Conversion: Most contexts will automatically convert the
const char[6]array to aconst char*pointer pointing to the first character. For example, if you pass"hello"to a function expecting a pointer, or assign it to a pointer variable, you’re no longer dealing with the array type directly. - Misusing
sizeof:sizeof("hello")will return6(the full size of the array), butsizeof(const char*)returns the size of a pointer on your system (usually 4 or 8). If you’re accidentally taking the size of a pointer instead of the array, that might lead to confusing values. - Pointer Comparisons: If you’re comparing pointers to string literals, keep in mind that the compiler may store identical literals at the same memory address (or not, depending on compiler settings), which could result in unexpected equality/zero results.
Example to Verify the Type
Here’s a quick C++ snippet to confirm the underlying type using decltype (which preserves the original type of the literal):
#include <iostream> #include <typeinfo> int main() { // decltype("hello") retains the original const char[6] type using HelloType = decltype("hello"); HelloType arr = "hello"; std::cout << "Size of the string literal array: " << sizeof(arr) << "\n"; // Outputs 6 std::cout << "Type name (compiler-dependent): " << typeid(HelloType).name() << "\n"; return 0; }
内容的提问来源于stack exchange,提问作者Vincent
相关产品推荐
相关产品推荐

