Search code examples
c++c++14integer-overflowunsigned-integer

Further understanding of unsigned integer overflow in C++14


Why does the following code fail for the case of uint8_t?

#include <iostream>
#include <cstdint>
#include <stack>

template <typename TT>
void PrintNumberScientificNotation (TT number) {
  constexpr TT             kBase{10};          // Base of the numerical system.
            TT             xx{number};         // Number to convert.
            TT             exponent{};         // Exponent.
            std::stack<TT> fractional_part{};  // Values in the fractional part.

  do {
    fractional_part.push(xx%kBase);
    xx /= kBase;
    exponent++;
  } while (xx > kBase);

  std::cout << xx << '.';
  while (!fractional_part.empty()) {
    std::cout << fractional_part.top();
    fractional_part.pop();
  }
  std::cout << " x 10^" << exponent << std::endl;
}

int main () {
  uint8_t number_1{255};
  PrintNumberScientificNotation(number_1);  // Does not work.
  uint16_t number_2{255};
  PrintNumberScientificNotation(number_2);  // Works.
  uint16_t number_3{65'535};
  PrintNumberScientificNotation(number_3);  // Works.
  uint32_t number_4{4'294'967'295};
  PrintNumberScientificNotation(number_4);  // Works.
  uint64_t number_5{18'446'744'073'709'551'615};
  PrintNumberScientificNotation(number_5);  // Works.
}

Execute: http://cpp.sh/8c72o

Output:

. x 10^
2.55 x 10^2
6.5535 x 10^4
4.294967295 x 10^9
1.8446744073709551615 x 10^19

It is my understanding that uint8_t is able to represent unsigned integer numbers up to and including 255 (UINT8_MAX). Why can I represent the maximum values for all of the other representations?


Solution

  • The mathematical part of your code is fine, the printing is broken.

    If you use cout for uint_t, it will interpret the uint_t as a character code. That's because uint_t is a type alias for unsigned char.

    A possible fix is to explicitly convert to integer:

      std::cout << unsigned(xx) << '.';
      while (!fractional_part.empty()) {
        std::cout << unsigned(fractional_part.top());
        fractional_part.pop();
      }
      std::cout << " x 10^" << unsigned(exponent) << std::endl;