I have had a long discussion with a group of colleagues regarding the correct answer of the question in the following code section. I have relied on a couple of discussions here on stackoverflow.com about overflow in signed integers for my answer. So, I told them that the choices should contain "undefined behavior" and it should be the correct answer. But they said the answer should be (C) and they provided some links of the same question on many sites providing the same question and answer. I will quote the question, its answer and explanation as given in the links they provided. So, what should be the correct answer? Thanks
- What will be output if you will compile and execute the following c code?
#include<stdio.h>
int main() {
char c=125;
c=c+10;
printf("%d",c);
return 0;
}
Choices:
(A) 135
(B) +INF
(C) -121
(D) -8
(E) Compiler error
Explanation:
As we know char data type shows cyclic properties i.e. if you will increase
or decrease the char variables beyond its maximum or minimum value
respectively it will repeat same value according to following cyclic
order:
So,
125+1= 126
125+2= 127
125+3=-128
125+4=-127
125+5=-126
125+6=-125
125+7=-124
125+8=-123
125+9=-122
125+10=-121
Answer: (C)