Consider the following operation that overflows:
char c = 250;
c += 8;
What value does c have after the above statements are executed? (Give your answer as a decimal integer.)
Answers
Answer:
no answer for this question yet in my mind
Explanation:
Assuming c is signed, the overflow is undefined according to the C standard. In many implementations, setting c to 250 will overflow to -6, then adding 8 will make c 2. This is implementation dependant. –
dangee1705
Jan 1, 2019 at 21:02
Thanks a lot! Still I would like to ask that is there any possible way to solve this using binary addition? –
Kikky
Jan 1, 2019 at 21:07
The hint to use binary addition is that 250 is 11111010 in binary, and 8 is 1000, and their sum is 100000010, which is nine bits. If a char holds only the last eight bits, the first 1 is lost, and the value is 00000010, so the result is 2. However, this hint ignores the rules of C. If char is unsigned, this binary view of the arithmetic is okay; C’s modulo-wrapping rules are equivalent to discarding high bits. If char is signed, the rules of C may differ from this binary view; an implementation is allowed to do things other than use the low eight bits. –
Eric Postpischil
Jan 1, 2019 at 22:00
Note the is no casting done nor overflow here. There is assignment.