Вопрос

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

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top