Range of indexes not default initialized in arrays in C++

Multi tool use
Multi tool use


Range of indexes not default initialized in arrays in C++



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?




2 Answers
2



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.


false



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.


bool


false



the default value of boolean type variables is false.



It's not true here. For default initialization,


non-POD (until C++11)



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.


x


x






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

pQU 0Pj8Z8o
Bb,zeNSsGyIM nslZpDnv8,WjnoMn,48S0w3i4ksW3K5 O 5qn3INnehw

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

Audio Livestreaming with Python & Flask