Could someone please explain the difference in how the 2 snippets of code are handled below? They definitely compile to different assembly code, but I’m trying to understand how the code might act differently. I understand that string literals are thrown into read only memory and are effectively static, but how does that differ from the explicit static below?
struct Obj1
{
void Foo()
{
const char* str( "hello" );
}
};
and
struct Obj2
{
void Foo()
{
static const char* str( "hello" );
}
};
With your static version there will be only one variable which will be stored somewhere and whenever the function is executed the exact same variable will be used. Even for recursive calls.
The non-static version will be stored on the stack for every function call, and destroyed after each.
Now your example is a bit complicated in regards to what the compiler actually does so let’s look at a simpler case first:
And then a main something like this:
will print
whereas with
it will print
Now with your example you have a const, so the value can’t be changed so the compiler might play some tricks, while it often has no effect on the code generated, but helps the compiler to detect mistakes. And then you have a pointer, and mind that the static has effects on the pointer itself, not on the value it points to. So the string “hello” from your example will most likely be placed in the .data segment of your binary, and just once and live as long as the program lives,independent from the static thing .