Why is "int sum=ch1+ch2+ch2" not giving overflow when right-side operands are character variables & result >255? [duplicate]

StackOverflow https://stackoverflow.com/questions/16586182

Question

In this program I am attempting to assign the result of the addition of character variables to an integer variable.I have made sure that the size of the addition is greater than 255.So I expect an expression overflow on the right and even though the result is 362,due to overflow I expect 106 to be assigned after the result is cast to int,not 362.But strangely 362 is being assigned.

The result is the same irrespective of whether the characters are signed or unsigned.Why is there no overflow and 362 being assigned?Since there is no integer on the right side during addition and all operands are characters,I don't expect them to be promoted to int.

#include<stdio.h>

int main(void)
{

unsigned char ch1='z',ch2='x'; //Same result for signed too
int sum=ch1+ch2+ch2;
printf("%d",sum);

}
Was it helpful?

Solution

all calculation starts minimum at integer precision so your statement will work like following

int sum=(int)ch1+(int)ch2+(int)ch2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top