C++ Standard Library C++ STL Library

C++ <bitset> - flip() Function



The C++ bitset::flip function is used to flip the bit at specified position of the bitset. Along with this, it is also used to flip all bits of the bitset.

Syntax

//flip all bits
bitset& flip();

//flip single bit	
bitset& flip (size_t pos);
//flip all bits
bitset& flip() noexcept;

//flip single bit	
bitset& flip (size_t pos);

Parameters

pos Specify position of the bit whose value is flipped.

Return Value

*this

Exception

Version 1: never throws exception. Version 2: throws out_of_range, if specified position is not a valid bit position.

Example:

The example below shows the usage of bitset::flip function.

#include <iostream>
#include <bitset>
using namespace std;
 
int main (){
  bitset<4> bset("1011");
  
  cout<<"1. bset is: "<<bset<<"\n";

  //flip all bits
  bset.flip();
  cout<<"2. bset is: "<<bset<<"\n";

  //flip bit at specified position
  bset.flip(3);
  cout<<"3. bset is: "<<bset<<"\n";

  //flip bit at specified position
  bset.flip(3);
  cout<<"4. bset is: "<<bset<<"\n";

  return 0;
}

The output of the above code will be:

1. bset is: 1011
2. bset is: 0100
3. bset is: 1100
4. bset is: 0100

❮ C++ <bitset> Library