1

I want to know how is this program working:

#include <bitset>
#include <iostream>
 
const int option_1 = 0;
const int option_2 = 1;
const int option_3 = 2;
const int option_4 = 3;
const int option_5 = 4;
const int option_6 = 5;
const int option_7 = 6;
const int option_8 = 7;
 
int main()
{
    std::bitset<8> bits(0x2); 
    bits.set(option_5);
    bits.flip(option_6); 
    bits.reset(option_6); 
 
    std::cout << "Bit 4 has value: " << bits.test(option_5) << '\n';
    std::cout << "Bit 5 has value: " << bits.test(option_6) << '\n';
    std::cout << "All the bits: " << bits << '\n';
 
    return 0;
}

I have seen this example on a website, But cannot understand the working of some part of this program.
here, first option5 is set to 4, then in main program "bit.set(option5);" is used to set it to 1(is what i think). then what is use of that 4 assigned to integer option5 above??

1 Answer 1

3

So this is basically at a high level an array of bits. Using non type templating an array of bits is created on the stack.

The option5 variable is used to set the fourth bit (from the back when printed) to 1. So when you print out the values there is a 1 in the location pointed to by option5 which is location 4 from the back.

The constructor of the bitset is used to initialize the bitset to look like 0b00000010. The set() function sets the bit at the location specified to 1, the reset() function sets the bit at the location specified to 0.

Sign up to request clarification or add additional context in comments.

2 Comments

so in simple language, u mean that 4 is a address and not a value. am i right??
In a way yes! It is pointing to a location in the bitfield :) Very much like an index to an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.