c++ - Problem with multiplication of signed chars -


discussing this answer find out code bellow prints -1 , 1 in visual studio. why? in opinion should print 2 1s despit overflow during multiplication.

signed char c1 = numeric_limits<signed char>::min(); signed char c2 = -1; cout << c1 * c2 / c1 << endl; signed char result = c1 * c2; cout << result / c1 << endl; 

c1 might have value -128, say. in multiplication, integer promotions cause both c1 , c2 converted type int before operation performed.

c1 * c2 going int value 128 c1 * c2 / c1 going int value -1.

-1 first output looks correct me.

for second version, typically assignment of result of c1 * c2 won't fit signed char , convert implementation-defined result, perhaps -128 instead of 128.


Comments