What is the default value for member variable if not defined ?
-
Hi All,
I have a member variable which is of bool type and it's default value is not defined in the class. During my application execution, this particular class instance is created dynamically multiple times.
What i could observe is for all Android version this bool member variable is always getting set to false .
But for iOS version lower than 16.02 this bool variable is randomly setting the value to either true or false.
And for iOS version higher than 16.02, this bool variable is always setting to falseCan some one help me understand why the OS/compiler is setting random values for particular set of OS version alone?
Is there any documentation which could help me understand this concept ?
Thanks in advance!
-
@Vinoth-Rajendran4 said in What is the default value for member variable if not defined ?:
Is there any documentation which could help me understand this concept ?
There is no concept here - an undefined value is... undefined. It can contain anything.
-
@Christian-Ehrlicher : Thanks for the reply. Yes, since the variable is not initialized, the behavior is undefined as per c++ guidelines.
But i am curious why the value of that bool member variable is always false in all version of Android and in certain versions of iOS.
-
@Vinoth-Rajendran4 it is curious indeed! An interesting find.
But, as @Christian-Ehrlicher said - you should ignore this finding and always initialize your variables as soon as possible. Never depend on such platform-related quirks.
-
@Vinoth-Rajendran4 said in What is the default value for member variable if not defined ?:
But i am curious why the value of that bool member variable is always false in all version of Android and in certain versions of
Again: it's undefined. Don't know what else is to say. Noone initialized it for you.
-
It depends on the underlying memory management scheme of the OS. Your app is getting memory in big chunks (pages) and in some circumstances those pages might be zeroed before they're handed over to you. Android apparently does this for stack memory by default and you can also opt-in for heap zeroing.
In any case, as others said, this is a mechanism outside of the C++ language, and you should definitely not rely on it being there. Keep your app language correct and initialize your variables before use. -
And to add to @Chris-Kawa:
If you use C++11 or higher, you should init the members directly at their declaration:
bool m_foo = false;
. At least that's what I do.Regards