1

Consider following C code

int main() {
    signed char result = 129;
    printf("%d", result);
    return 0;
}

Assuming char is 8 bit, 129 causes overflow, hence result of printf will be -127. I'm clear with this part.

But when i try the following:

int main() {
    signed char a=100,b=3;
    signed char c= 4;
    signed char result = a*b/c;
    printf("%d", result);
    return 0;
}

Then as per the convention, as a and b are signed char, a*b will be a signed char. Hence, 300 will overflow, so, only LSB(least significant 8 bits should be considered). This will make it 44 and when divided by 4, it should print 11 and not 75. I'm confused here.

taurus05
  • 2,491
  • 15
  • 28
  • 5
    `a*b/c;` is performed after all the operands are promoted to `int`, so no overflow is happening. `75` is the correct result. – Eugene Sh. Mar 09 '22 at 16:39
  • 1
    See [Implicit Conversions](https://en.cppreference.com/w/c/language/conversion) under Integer Conversions: [if the target type cannot hold the value] and if the target type is signed, the behavior is implementation-defined (which may include raising a signal). This applies to the first example. – JohnFilleau Mar 09 '22 at 16:41
  • @EugeneSh. so, firstly the result of a*b is determined. But this temporary result is stored as int, instead of signed char? automatic promotion is happening or is it called something else? – taurus05 Mar 09 '22 at 16:41
  • You say: "`a*b` will be a `signed char`". That's wrong. It will be an `int`. – Adrian Mole Mar 09 '22 at 16:42
  • @AdrianMole why will it be an int, when the variable type is an `signed char`?shouldn't the intermediate results be of the same data type as that of operands? – taurus05 Mar 09 '22 at 16:44
  • It's the rules of C. There's surely a duplicate around somewhere, about arithmetic operators, operands and integer promotions ... – Adrian Mole Mar 09 '22 at 16:49
  • More specifically, your values undergoes [*usual arithmetic conversions*](https://en.cppreference.com/w/c/language/conversion#Usual_arithmetic_conversions), which leads to *integer promotion*. – Some programmer dude Mar 09 '22 at 16:51
  • OK - Found a FAQ and will close this as a duplicate. If anyone finds better targets, ping me and I'll add them to the close banner. – Adrian Mole Mar 09 '22 at 16:52
  • @JohnFilleau gotcha! Thanks for sharing it. – taurus05 Mar 09 '22 at 16:56
  • @Someprogrammerdude i got it.Thanks! – taurus05 Mar 09 '22 at 16:57

0 Answers0