Search code examples
c++printfbitset

C++ bitset strange value


#include <bitset>
#include <assert.h>
#include <stdio.h>
using namespace std;


int main()
{
    bitset<128> bs(42);
    bs[11]=0;
    bs[12]=1;
    assert(bs[12]==1);
    printf("bs[11]=%d\n", bs[11]);
    printf("bs[12]=%d\n", bs[12]);
    return 0;
}

console output: enter image description here

Why can't I simply get 0 or 1 as output ?


Solution

  • printf with %d is for integer values, whereas std::bitset::operator[] returns a std::bitset::reference.

    You can use std::cout from <iostream> header (which is anyway a more c++ "way" to print to the console):

    #include <bitset>
    #include <assert.h>
    #include <iostream>
    
    int main()
    {
        std::bitset<128> bs(42);
        bs[11] = 0;
        bs[12] = 1;
        assert(bs[12] == 1);
        std::cout << "bs[11]=" << bs[11] << std::endl;
        std::cout << "bs[12]=" << bs[12] << std::endl;
        return 0;
    }
    

    Output:

    bs[11]=0
    bs[12]=1
    

    A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.