2

For signed char in C, the range is from -128 to 127. How can a+1 (as in the code), produce 128 and not -128? The subsequent increment is normal (-127 for both a and i).

#include<stdio.h>
int main()
{
    char i=127,a=127;
    printf("%d\n",++i);//output is -128
    printf("%d\n",a+1);//output is 128
    //subsequent increment after this is -127 for a and i.
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Shivani
  • 85
  • 5

1 Answers1

8

When used with arithmetic operators, all small integer types (bool, char, short) are subjected to integer promotions before any arithmetic is perfomed on them. In the a + 1 expression your a is promoted to int meaning that this expression is actually interpreted as (int) a + 1. The range of char plays no role here. All calculations are performed in the domain of int and the result has int type. 127 + 1 is 128, which is what you see printed.

Your ++i is defined as i = i + 1. For the same reasons the right-hand side is calculated as (int) i + 1, meaning that in this case the addition is performed in the domain of int as well. Later the result is converted back to char and stored back into i. The addition itself does not overflow and produces 128, but the subsequent conversion back to char "overflows", which produces implementation-defined behavior. In your case that implementation-defined behavior produced the value of -128 as char result.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 1
    Just for completeness the `%d` format in `printf("%d\n",++i);` then works because the `char` is then promoted back to an `int` as a default promotion in the variadic argument rules! – Persixty Jun 29 '17 at 07:19
  • @AnT, citing to what you said, I have a doubt in (a+1). "All calculations are performed in the domain of int and the result has int type. 127 + 1 is 128, which is what you see printed." I am convinced of this;but consider next increment of a=128.(a+1 again).The output prints as -127; not 129, as you consider should happen for a. – Shivani Jun 30 '17 at 15:36
  • @Shivani: This fails at the very beginning. `a=128` is already out of range with implementation-defined behavior. In your implementation `a = 128` is equivalent to `a = -128`. Only after that `a + 1` is calculated as I described above and expectedly produces `-127` result. – AnT stands with Russia Jun 30 '17 at 15:44