I have the following signed integers:
(4bits)a = 6;
(4bits)b = 7;
(4bits)c;
c = a + b;
Will c = 13 or c= -3?
If I do binary math and assume it’s a 4 bit number:
0110+0111=1101 (-8 + 4 + 0 + 1) = -3
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Contrary to popular belief, C does have 4-bit integer types. However, it doesn’t have objects of those types, only bit-fields (6.7.2.1/9, “A bit-field is interpreted as a signed or unsigned integer type consisting of the specified number of bits”):
The output of this program with my compiler is
-3, however this is not guaranteed by the standard. The reason is that the expressiona.value + b.valuehas typeint(because of integer promotion rules, 6.3.1.1/2), and value 13. The value 13 cannot be represented in a 4 bit signed integer, and therefore one of two things happens: either an implementation-defined result or an implementation-defined signal (6.3.1.3/3).In short, all you can do is check your compiler documentation, or run the code and see what it does. But this result, -3, is pretty natural for an implementation with 2s complement representation of signed integer types.
The value can’t be 13, because 13 is not in the range of values representable by a 4 bit signed integer. Anything is permitted as long as the implementation documents it, for example it could naturally be -2, on a 1s’ complement machine with no overflow checking. Not that you’ll likely ever encounter such a machine…
That’s something of a special case because the only way to get a 4 bit integer type is as a bit-field. In general, overflow of signed integer arithmetic is undefined behavior (6.5/5, “result is … not in the range of representable values for its type”). There’s no arithmetic overflow in your example because of the promotion to
int, so the range of behavior available to the implementation is limited – it’s not allowed to format your hard drive. But if you do overflow anintthen you’re totally at the mercy of your compiler.