'Sizeof string literal
The following code
#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;
}
outputs
sizeof(string literal) = 2
sizeof(const char* const) = 4
sizeof(const char[]) = 2
on a 32bit OS, compiled with GCC.
- Why does
sizeofcalculate the length of (the space needed for) the string literal ? - Does the string literal have a different type (from char* or char[]) when given to
sizeof?
Solution 1:[1]
sizeof returns the size in bytes of its operand. That should answer question number 1. ;) Also, a string literal is of type "array to n const char" when passed to sizeof.
Your test cases, one by one:
"f"is a string literal consisting of two characters, the characterfand the terminating NUL.foois a pointer (edit: regardless of qualifiers), and pointers seem to be 4 bytes long on your system..- For
barthe case is the same as"f".
Hope that helps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
