0

I have a pretty simple question about how intermediate results are type-inferred in C. For example, I want to take a convolution operator that takes a weighted sum of an 8 bit image and outputs an 8-bit image. In order to do this without overflow, I would perform the additions in 16-bit and bit shift/divide it back to 8 bits for the result array. I'm wondering how verbose I need to be to accomplish this without overflow. For example:

uint8_t a,b = 255;
uint16_t = (uint16_t)a + (uint16_t)b;

I know this would work. But what about this:

uint8_t a,b = 255;
uint16_t = a + b;

Do I know that the addition is being accumulated to a 16-bit int without overflow, or is it possible that the compiler could implement this as an 8-bit addition then cast to 16-bit (in which case this would overflow)? I think this should work in GCC, but I guess I'm asking if this scenario is defined standard behavior or left up to the compiler?

A Tyshka
  • 3,830
  • 7
  • 24
  • 46
  • 1
    Check out https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules – Nate Eldredge Oct 25 '21 at 01:38
  • The behavior is specified by the standard, but depends to some extent on how large the standard types like `int` are on your implementation. Assuming 32-bit `int` which is the case for most GCC targets, both operands get promoted to `int`, the addition is done as `int` (which here cannot overflow), the result of the addition has type `int`, and it is then converted to `uint16_t` which in this case cannot overflow either. – Nate Eldredge Oct 25 '21 at 01:41

0 Answers0