Is there any hidden feature of the sizeof
keyword I'm missing here when it's applied to a literal and not a pointer initialized to another literal?
#include <iostream>
int main(int argc, char* argv[]) {
const char* string = "Hello, World!";
// sizeof(...) on literal; returns 14 (the actual length)
std::cout << "sizeof (with literal): " << sizeof("Hello, World!") << std::endl;
// sizeof(...) on initiated pointer; returns 4 (wonder why?)
std::cout << "sizeof (with variable): " << sizeof(string) << std::endl;
return 0;
}
Or is it just my compiler "optimizing" the source?
The question here may seem to answer my question, but only partially.
The answer provided makes note on C++ not being able to pass entire arrays as function parameters and as such receiving array arguments as pointers instead
(Which logically, argument pointers could be of any size).
To which I can guess here that the literal is probably optimized to be a fixed-sized array and the pointer has an arbitrary size during compile-time, but the question is: why?
It's easier to wrap my head around this if the variable had been uninitialized:
char* string; // Arbitrary size that's mutable (usually 4 bytes)
but not in this case scenario when its initiated to a fixed-size literal:
const char* string = "Hello, World!"; // Fixed-size of 14 allocated to variable?
After all the valid characters of the variable had been specified in initiation (which implicitly gives a length by the number of characters initialized), would that not make the variable inherit the allocated size of the literal?