typedef struct foo
{
bool my_bool;
int my_int;
} foo;
In the example above I understand that my_bool will be initialized randomly to either true or false but what about my_int? I assumed that my_int would be default initialized to 0 but that seems not to be the case.
Defining structs in this way appears to be incompatible with initialization lists so what is the best way to initialize my_bool and my_int to false and 0 respectively?
Types don’t get “initialized”. Only objects of some type get initialized. How and when they get initialized depends on how and where the corresponding object is defined. You provided no definition of any object in your question, so your question by itself doesn’t really make much sense – it lacks necessary context.
For example, if you define a static object of type
fooit will be automatically zero-initialized because all objects with static duration are always automatically zero-initialized.
If you define an automatic object of type
foowithout an initializer, it will remain uninitializedIf you define an automatic object of type
foowith an aggregate initializer, it will be initialized in accordance with that initializerIf you allocate your object with
newand provide no initializer, it will remain uninitializedBut if you use the
()initializer, it will be zero-initialzedIf you create a temporary object of type
foousing thefoo()expression, the result of that expression will be zero-initializedSo, once again, in your specific case the initialization details depend on now you create the object of your type, not on your type itself. Your type itself has no inherent initialization facilities and doesn’t interfere with the initialization in any way.