Why is a bool type 2d array not holding 0 and 1?

Viewed 119

I run the program and see that the values aren't always 0 and 1. But this is a bool data type right?

#include<iostream>
#include<math.h>

using namespace std;

int main()
{
    bool arr[5][5];
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}
2 Answers

You are not initializing the array, the printed values are garbage stored in the memory where your declared array now lives, since you don't initialize it we can't know what's there.

Note that the size of a bool is implementation defined so we can't really guess a range of values for the aforementioned undefined behavior when printing unitialized members of the array.

The usual behavior we see is the compiler using the most efficient available type which usually means an unsigned 1 byte/8 bit wide type. In this situation you could expect the uninitialized values to be in the range of 0 to 255.

To initialize all the values in the array you could do this:

bool arr[5][5]{};

With this value initialization the array would be zero initialized and your program would output:

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 

You can use boolalpha to print actually true or false:

Example:

https://godbolt.org/z/xvh67jWWK

You are experiencing undefined behavior due to reading uninitialized values.

The presence of UB makes program behavior meaningless. The reason you see random garbage which is not only 0 or 1 is because bool occupies one byte, not one bit. The compiler does not compensate for this because in a valid program such situation is impossible, so there is no need to do the extra work.

If you initialize the bool array properly, the issue will be resolved:

bool arr[5][5] = {};

See this related question in which, due to UB a bool is both true and false at the same time.

Related