Question

This question arose from a discussion I was having about the correct way to output a numeric value using the usual ostream & operator << (ostream &, some_type) for a numeric type in C++.

The way I'm familiar with the behavior of std::showbase and std::showpos in each base, they are basically mutually exclusive. That is: in decimal no base is shown, and the '+' is added on positive numbers; whereas in hexadecimal or octal, the base is shown, but a '+' is not shown (nor is a minus), as the value of the type is printed as if it's cast to an unsigned type.

For example, this simple (verbose) program:

#include <iostream>

int main() {
  std::cout << std::dec << std::showpos << std::showbase << int64_t(+5) << std::endl;
  std::cout << std::oct << std::showpos << std::showbase << int64_t(+5) << std::endl;
  std::cout << std::hex << std::showpos << std::showbase << int64_t(+5) << std::endl;
  std::cout << std::dec << std::showpos << std::showbase << int64_t(-5) << std::endl;
  std::cout << std::oct << std::showpos << std::showbase << int64_t(-5) << std::endl;
  std::cout << std::hex << std::showpos << std::showbase << int64_t(-5) << std::endl;
}

Gives this output when compiled with GCC:

+5
05
0x5
-5
01777777777777777777773
0xfffffffffffffffb

This is what I've always expected, having used C++ for many years, but is this really guaranteed by the standard, or is this just common behavior? For example, could a standard-compliant C++ compiler output one of these sequences instead?

+5
+05
+0x5
-5
01777777777777777777773
0xfffffffffffffffb

or even:

+5
+05
+0x5
-5
-05
-0x5

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top