Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ bool to int cast and GCC 4.8.1

Do I understand correctly that bool to int cast should cast true to 1?

GCC 4.8.1 gives strange result for this code:

#include <array>
#include <iostream>

int main()
{
    using namespace std;

    array<bool, 3> bb;
    for ( int i = 0; i < 3; i++ ) cout << static_cast<int>( bb[i] ) << endl;

    return 0;
}

Here is what I get:

>> g++ -std=c++11 test_bool.cpp  -pedantic -O3
>> ./a.out 
136
251
160
like image 518
user2052436 Avatar asked Dec 08 '25 23:12

user2052436


1 Answers

Do I understand correctly that bool to int cast should cast true to 1?

Yes.

GCC 4.8.1 gives strange result for this code:

That's because your program has undefined behavior, since your array is not initialized. Try, for instance, this:

array<bool, 3> bb = { true, false, true };

And you will see a consistent output. Here is a live example.

like image 192
Andy Prowl Avatar answered Dec 10 '25 11:12

Andy Prowl