Solved implicit initialization
-
I am trying to determine if structs will be initialized if defined outside a function in a compilation unit:
... typedef struct SomeStruct{ int somevalue; } buncha_structs[256]; ... int main(){ SomeStruct local_structs[256]; }
If I am understanding this correctly. Then bunch_structs is initialized, but local_structs are not and require explicit initialization. Is this true? I am having trouble testing this out. I can test this out with the new operator by creating a memory pool and feeding a pointer to that pool to new(pool). Cannot think of a way to test this with a struct array outside of a function.
-
@fcarney
Yes, and also as per reading the link you referenced, your understanding is correct. Static/global storage declarations will be initialized to 0, but local/stack will be uninitialized. This would be just as true if your variable wasint
instead ofstruct ...
.I'm not sure why you cannot think how to test this. I have gone to http://cpp.sh and pasted:
// Example program #include <iostream> #include <string> struct SomeStruct { int somevalue; } buncha_structs[256]; int main() { SomeStruct local_structs[256]; std::cout << local_structs[1].somevalue << std::endl; std::cout << buncha_structs[1].somevalue << std::endl; }
available as http://cpp.sh/5gbae (don't know how long that link is valid).
Note that I think you did not intend the
typedef
in your code. With thetypedef
, yourbuncha_structs
is a type not a variable. I have removed thetypedef
to give you a global variable, which I think is what you intended.The above reliably outputs 0 for the second, global variable case, but outputs a "random", changing number each time for the first, local case. You should also see that it shows an "uninitialized" warning message against your use in the local variable case.
-
One issue I ran into was my local variables were showing zeros as well. It wasn't until I inited the ram with 255 for every character and used new(mempool()) to use that preinited ram that I did see uninitialized ram. Of course that was on the heap and not the stack. I did test this over the weekend and observed what you said. Variables declared outside of local scope are initialized to zero. While stack and heap are not.