-1

Can someone explain the result of this? Please explain step by step clearly. Thanks a lot.

Why it's -16, -6, - 22? How compiler got these value?

Here's the code:

int main(void)
{
    char i=240, j=250, sum;
    sum = i+j;
    printf("Result is: %d + %d = %d\n",i,j,sum);

    return 0;
}

Here is the result: Result is: -16 + -6 = -22

田睿霖
  • 33
  • 5

2 Answers2

1

Because Char is 8 bits and it's capacity is 255

When you add i+j you put ‭490‬ in sum

Then sum variable overflow and it generate negative number

Use int instead of char for sum variable it will solve your problem

Read https://www.cquestions.com/2011/02/char-overflow-in-c.html for more information

Mohammad Ansari
  • 1,076
  • 1
  • 11
  • 22
0
char i=240

Overflow. char = 8 bits. When signed, it ranges from -128 to 127. So this converts it to negative.

Suggestion: read your compiler's warnings carefully.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78