Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Why does cout print large integers from a boolean array?

Tags:

c++

cout

#include <iostream>
using namespace std;

int main() {
    bool *a = new bool[10];

    cout << sizeof(bool) << endl;
    cout << sizeof(a[0]) << endl;

    for (int i = 0; i < 10; i++) {
        cout << a[i] << " ";
    }

    delete[] a;
}

The above code outputs:

1
1
112 104 151 0 0 0 0 0 88 1 

The last line should contain garbage values, but why are they not all 0 or 1? The same thing happens for a stack-allocated array.

Solved: I forgot that sizeof counts bytes, not bits as I thought.

like image 557
Alan Avatar asked Nov 29 '25 12:11

Alan


2 Answers

You have an array of default-initialized bools. Default-initialization for primitive types entail no initialization, thus they all have indeterminate values.

You can zero-initialize them by providing a pair of parentheses:

bool *a = new bool[10]();

Booleans are 1-byte integral types so the reason you're seeing this output is probably because that is the data on the stack at that moment that can be viewed with a single byte. Notice how they are values under 255 (the largest number that can be produced from an unsigned 1-byte integer).

OTOH, printing out an indeterminate value is Undefined Behavior, so there really is no logic to consider in this program.

like image 101
David G Avatar answered Dec 02 '25 00:12

David G


sizeof(bool) on your machine returns 1.

That's 1 byte, not 1 bit, so the values you show can certainly be present.

like image 26
Drew Dormann Avatar answered Dec 02 '25 02:12

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!