Reputation: 1290
My understanding is that static variables get put in the uninitialized variable section of the binary (the BSS section) and so those are safe to assume as being initialized to 0.
But I have a function defined in an unnamed namespace. Inside the function, there is a char array declared without being explicitly initialized to 0. Will this be auto-initialized to 0? What about variables not declared as static but defined in an unnamed namespace? And what about local variables of static functions?
Upvotes: 1
Views: 1560
Reputation: 88225
A function local variable will not be automatically initialized to zero, regardless of whether the function is in an anonymous namespace, static, or whatever. This is because the local variables inside a function are not static variables. To cause a local variable to have static storage duration you must explicitly mark it with static
.
int foo; // static storage duration (because it's global) automatically zero-initialized
static int foo2; // static storage duration (because it's global) automatically zero-initialized. The static keyword just gives the name 'foo2' internal linkage and has nothing to do with static storage duration.
namespace {
int foo; // static storage duration, automatically zero-initialized
void bar() {
int f; // local variable, not automatically zero-initialized
static int g; // static storage duration (because of the keyword static), automatically zero-initialized
}
}
Upvotes: 3
Reputation: 2843
You can't rely on a variable being automatically initialized to any value. Even if this happens constantly in some cases, just changing the compiler could produce totally different results. Safest is to always initialize every variable to be sure of its value. You should also initialize static variables. The fact that a variable belongs to a namespaces does not matter.
Upvotes: 1
Reputation: 2912
Don't ever rely on something being initialized/done for you. Just do the initialization always as things may change and you will be caught unaware.
Upvotes: 1