Search code examples
c++ioformatted

How does ios::fmtflags works in C++?How setf() works?


I am trying to understand formatted flags of ios stream. Can anyone please explain how this cout.setf(ios::hex | ios::showbase) thing works? I mean how does the or (|) operator work between the two ios formatted flags? Please pardon me for my bad english.


Solution

  • std::ios_base::hex and std::ios_base::showbase are both enumerators of the BitmaskType std::ios_base::fmtflags. A BitmaskType is typically an enumeration type whose enumerators are distinct powers of two, kinda like this: (1 << n means 2n)

    // simplified; can also be implemented with integral types, std::bitset, etc.
    enum fmtflags : unsigned {
        dec      = 1 << 0, // 1
        oct      = 1 << 1, // 2
        hex      = 1 << 2, // 4
        // ...
        showbase = 1 << 9, // 512
        // ...
    };
    

    The | operator is the bit-or operator, which performs the or operation on the corresponding bits, so

    hex             0000 0000 0000 0100
    showbase        0000 0010 0000 0000
                    -------------------
    hex | showbase  0000 0010 0000 0100
    

    This technique can be used to combine flags together, so every bit in the bitmask represents a separate flag (set or unset). Then, each flag can be

    • queried: mask & flag;

    • set: mask | flag;

    • unset: mask & (~flag).