Reputation: 80
The following is the code I am trying to run
#include<bits/stdc++.h>
using namespace std;
int main()
{
bool x[101010];
for(int i=0;i<101010;i++)
{
if(x[i])
cout<<i<<" ";
}
return 0;
}
As far as I know, the default value of boolean type variables is false. However, for the above code from index 94758-101008 value of i is being printed which means they are default initialized as true.
Can anyone please help me in figuring out where am I going wrong?
Upvotes: 0
Views: 42
Reputation: 170299
Your problem can be reduced to this:
bool x;
std::cout << x;
A boolean is a fundamental type. Default initializing automatic variables of a fundamental type leaves them with indeterminate values. Not false
, but indeterminate. Using those values leads to undefined behavior. This is what you are seeing.
The reason you see random values is that "behind the curtain" a boolean is an integer type that the compiler enforces only two values on. But if you don't initialize it explicity, you'll get whatever random junk is that memory.
The solution is to explicitly value-initialize your variables. For an array, it would look like this:
bool x[101010]{};
That will recursively value initialize each element of the array, and to value initialize a bool
is indeed to set it to false
.
Upvotes: 3
Reputation: 173044
the default value of boolean type variables is false.
It's not true here. For default initialization,
- if T is a
non-POD (until C++11)
class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object;- if T is an array type, every element of the array is default-initialized;
- otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.
x
is declared as local object with automatic storage duration, and it's an array with non-class type; then the value of all the elements of x
will be indeterminate values.
Upvotes: 1