Suppose I have a struct called foo_boolean that contains some boolean values:
struct foo_boolean {
bool b1;
bool b2;
};
If I define a variable of type foo_boolean without initializing it, what will the default value of the member variables be? (i.e., true, false, or a random value of the two.)
The default value of the bool type is false .
If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable). If it's declared within a method you will still have to initialize it to either true or false, or there will be a compiler error.
The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false). All the values stored in the array in the above program are garbage values and are not fixed.
To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0.
It depends on how you create it. If the struct is constructed by default-initialization e.g.
void foo () {
fool_boolen x; // <---
then the values will be undefined (bad things will happen if you read it before setting a value).
On the other hand, if the struct is constructed by value-initialization or zero-initialization e.g.
fool_boolen x; // <--
void foo2 () {
static fool_boolen y; // <--
fool_boolen z = fool_boolen(); // <--
then the values will be zero, i.e. false.
The value of the bool
will is undefined. It will be whatever else was on the stack before it, which is sometimes zeroed out if nothing has used it previously.
But again, it is undefined, which means it can be either true or false.
If you need a default value, you can do:
struct fool_bool {
bool b1;
bool b2;
fool_bool() {
b1 = true;
b2 = false;
}
};
This makes b1 true by default, and b2 false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With