1

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.

Anirban166
  • 3,162
  • 4
  • 11
  • 27
  • Read the source. It's complicated code and it's not modern and idiomatic by current standards though. Also, step through the code with a debugger. For reference, try getting hold of "C++ IOStreams and Locales", it explains pretty much everything concerning these parts of the standard library. – Ulrich Eckhardt Feb 15 '20 at 08:12

1 Answers1

1

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).

L. F.
  • 16,219
  • 7
  • 33
  • 67