Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is type if uint8_t value multiplied by uint8_t [duplicate]

Tags:

c++

What is type if uint8_t value multiplied by uint8_t? For example:

#include <iostream>

int main()
{
    uint8_t a = 'a', b = 'b';
    std::cout << a * b;
}

The output of the program is 9506. Will a * b be uint32_t type data?
Why not still be a uint8_t type?
Thanks.

like image 662
leiyc Avatar asked Oct 17 '25 07:10

leiyc


1 Answers

Due to integer promotion rules in C++ integer types narrower than int in usual arithmetic operations are promoted to int before the operation is applied (simplified explanation).

You can observe this at https://cppinsights.io/ (neat tool right?):

#include <cstdint>

int main()
{
    uint8_t a = 'a', b = 'b';
    [[mayebe_unsued]] auto r = a * b; // <-- pay attention here
}

is converted internally by the compiler to:

#include <cstdint>

int main()
{
  uint8_t a = static_cast<unsigned char>('a');
  uint8_t b = static_cast<unsigned char>('b');
  int r = static_cast<int>(a) * static_cast<int>(b); // <-- pay attention here
}

As to why, well, it was considered wayback that operations with operands in the platform native type (int) are faster than with operands with narrower types. I honestly don't know how much truth is to this in modern architectures.

like image 72
bolov Avatar answered Oct 19 '25 22:10

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!