Overflow in C
2 min read
This page was translated by AI
I encountered a problem while solving exercises in class today. Running the following code prints negative numbers:
#include <stdio.h>
int main()
{ char c1,c2;
c1=197;
c2=198;
printf("c1=%d,c2=%d\n",c1,c2);
return 0; }GPT explained it this way:
This code prints negative numbers because
charin C is commonly treated as a signed character type (signed char) with a range of -128 to 127. Therefore, assigning an integer greater than 127 to acharvariable causes overflow.When you assign an integer to a
charvariable, truncation and overflow occur.charis commonly a signed character type with a range of -128 to 127, although this can vary by compiler and platform. Acharcan represent only integers within that range, so values outside it overflow and produce an unexpected result.In this code,
c1andc2are assigned 197 and 198. Here is whyc1prints as -59:
- First, understand that
charranges from -128 to 127.- Both 197 and 198 are outside that range.
- Because
charis signed, out-of-range integers are interpreted as signed values.- Computers use two’s complement to represent signed integers. In two’s complement, the highest bit is the sign bit: 0 means positive and 1 means negative.
- When 197 is assigned to
c1, the computer converts it to binary. Its highest bit is 1, so the value is treated as negative.- The 8-bit binary representation of 197 is
11000101. Since its highest bit is 1,c1is interpreted as negative.- Computers convert negative numbers to signed integers using two’s complement. In two’s complement, the absolute value is converted to binary, inverted, and incremented by 1. Inverting
11000101gives00111010; adding 1 gives00111011.00111011is 59 in decimal, but because the highest bit is 1,c1is interpreted as -59.- Similarly, assigning 198 to
c2overflows and it is interpreted as -58.Therefore, after overflow,
c1andc2are -59 and -58 respectively, which is why negative numbers are printed.
After looking into it further, I found that char variables in C are commonly signed
character types with a range of -128 to 127. Values outside that range are interpreted as
signed integers. Computers use two’s complement to represent signed integers, which is why
the result becomes negative.