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
Patricia ArquetteOriginal
2024-12-02 17:19:10662browse

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;
}

Executing this code reveals intriguing results:

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

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!

Statement:
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