0

For this code:

int main(int argc, char **argv)
{
    auto a =     static_cast<uint8_t>(sizeof(uint64_t));
    auto b = 8 * static_cast<uint8_t>(sizeof(uint64_t));

    auto c =     static_cast<uint32_t>(sizeof(uint64_t));
    auto d = 8 * static_cast<uint32_t>(sizeof(uint64_t));

    return EXIT_SUCCESS;
}
  • The type of a resolves to unsigned char,
  • The type of b resolves to int,
  • The type of c resolves to unsigned int and,
  • The type of d resolves to unsigned int

I expect these results for a, c, and d, but I'm baffled by b.

64 clearly fits in a 8-bit unsigned char. Can anyone explain, please?

casting to auto

Blair Fonville
  • 908
  • 1
  • 11
  • 23
  • 1
    Related: https://stackoverflow.com/q/5563000/1896169 , https://stackoverflow.com/q/6770258/1896169 – Justin Mar 29 '18 at 23:44
  • It does not hurt to read the documentation. – Phil1970 Mar 30 '18 at 00:25
  • 1
    @Phil1970 What documentation? The C++ documentation? You mean the standard? I got a great answer in 3 minutes (literally). I can't image how long it would have taken me to look it up in the standard. – Blair Fonville Mar 30 '18 at 00:27
  • @BlairFonville You could even be much faster that that by using **Google**. In less than 10 seconds, you can find that page: http://en.cppreference.com/w/cpp/language/implicit_conversion. – Phil1970 Mar 30 '18 at 00:53
  • @Phil1970 Yes, if I had already known the answer I could have found it on Google almost immediately. – Blair Fonville Mar 30 '18 at 00:54

1 Answers1

5

You're not "casting to auto" (which would be meaningless/impossible); auto, as it always does, is triggering the compiler to take the type of the expression on the RHS. That type is governed not by runtime values and how many bits you have, but by the standard. And the standard's integer promotion rules mean that the result of a multiplication is an int type, not char. No integer promotion is required when the expression is already an int type, though, so d keeps the unsignedness of its right-hand operand.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055