Home > Backend Development > C++ > What's the Difference Between `sizeof` a String Literal, a `const char* const`, and a `const char[]`?

What's the Difference Between `sizeof` a String Literal, a `const char* const`, and a `const char[]`?

Patricia Arquette
Release: 2024-12-02 17:19:10
Original
654 people have browsed it

What's the Difference Between `sizeof` a String Literal, a `const char* const`, and a `const char[]`?

Sizeof String Literal: Unraveling the Differences

Consider the following code snippet:

#include <iostream>
using namespace std;

int main()
{
    const char* const foo = "f";
    const char bar[] = "b";
    cout << "sizeof(string literal) = " << sizeof("f") << endl;
    cout << "sizeof(const char* const) = " << sizeof(foo) << endl;
    cout << "sizeof(const char[]) = " << sizeof(bar) << endl;
}
Copy after login

Executing this code reveals intriguing results:

sizeof(string literal) = 2
sizeof(const char* const) = 4
sizeof(const char[]) = 2
Copy after login

Understanding the Results

  • sizeof("f"): This evaluates to 2, as it includes the character 'f' and the terminating null character '

The above is the detailed content of What's the Difference Between `sizeof` a String Literal, a `const char* const`, and a `const char[]`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template