-1
#include <stdio.h>
int main(void)
{
    char a, b;
    int c;

    b = 2;
    a = 127;
    c = a + b;
    printf("%d", c);
}

i thought the value of the c should be -127 ,but actually when i run this test,the value is 129.

according to an example from <<c pragramming:a morden approach>>,

long int i;
int j=1000;

i=j*j;  /*overflow may occur,correct writing is i=(long)i*i;

here is the explain of the book--When two int type values are multiplied, the result should also be int, but the result of j * j is too large to be consistent and cannot be expressed as int on some machines, resulting in overflow.

so i think in my test,the type of (a+b) is char,because 129>127..char cannot express 129, which will cause overflow. i am very confused

Barmar
  • 741,623
  • 53
  • 500
  • 612
Mapleton
  • 1
  • 1

1 Answers1

1

What happens in the first piece of code is the result of integer promotions. This means that any integer value with a type smaller than int (like char or short) is first promoted to type int before being used in an expression.

In this case:

 c = a + b;

a and b both have type char, and their values are both promoted to int. So what is being added is the int value 2 and the int value 127 which is 129.

The difference between the first piece of code and the second piece of code is that no promotion happens in the second case. The variable j already has type int so the value is not promoted. Casting one of the arguments to long causes the multiplication to happen with type long.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • The integer promotion applies when the value is used as operand of certain operators. This is specified under each such operator in the standard. There are many other expressions where values are not promoted. – M.M Feb 20 '20 at 03:46