3

Today i was trying some types defined in the cstdint header file: std::uint16_t, std::uint_least16_t and so on..

I think they are very useful because you know exactly or at least how big they are, unlike the more common platform-specific ones: int, unsigned int, and so on.. But there is one problem that I think can cause many errors.

Let's say we have this code:

#include <cstdint>
#include <iostream>

int main()
{
  std::uint_fast16_t test = 0;

  test = 65536;

  std::cout << test;

  return 0;
}

We know that std::uint_fast16_t should be AT LEAST 2 bytes.

If the uint_fast16_t is exactly 2 bytes, this code gives a warning because of the overflow. But in my case the uint_fast16_t is 8 bytes (checked it previously).

So in my case this code compiles and runs fine, in the other we get a warning. Our code isn't portable. This is just wrong for me. Even if the variable can hold that data, the compiler should at least give us a warning or suggesting us to use a bigger type. Am i right? Or did i misunderstand the purpose of those types?

I compiled the code using g++ with these flags

-Wall -Werror -pedantic -std=c++0x

Grizzly
  • 18,279
  • 3
  • 56
  • 75
Gaudo
  • 73
  • 1
  • 4
  • 2
    I was complaining about something similar in a different language, and the basic response was: `uint_blahblah` is just a different name for a built-in type, not a separate type. So don't use it if you need type checking for something like this. – user541686 May 29 '12 at 23:49

1 Answers1

4

Compiler cannot provide any other warning, because those types are typedefs and they're treated exactly as the types they're synonyms to. That's how C++ works. You have UINT_FAST16_MAX and possibly std::numeric_limits<std::uint_fast16_t>::max() to tell you the maximum value this type can hold. It's your job to use that information.

Also keep in mind most of types defined by stdint are actually optional, so just by using them and not checking if they're exist you make your code unportable.

Cat Plus Plus
  • 113,388
  • 26
  • 185
  • 215
  • With careful coordination between the compiler and library, the compiler could provide intrinsic types that the library could typedef. – James McNellis May 30 '12 at 00:03
  • I see.. maybe i'm just going to write my own class which extends those types using that limit. As long as i use uint_fast and uint_least types my code should be portable anyway, am i right? – Gaudo May 30 '12 at 00:21