skip to content

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 char in 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 a char variable causes overflow.

When you assign an integer to a char variable, truncation and overflow occur. char is commonly a signed character type with a range of -128 to 127, although this can vary by compiler and platform. A char can represent only integers within that range, so values outside it overflow and produce an unexpected result.

In this code, c1 and c2 are assigned 197 and 198. Here is why c1 prints as -59:

  1. First, understand that char ranges from -128 to 127.
  2. Both 197 and 198 are outside that range.
  3. Because char is signed, out-of-range integers are interpreted as signed values.
  4. 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.
  5. When 197 is assigned to c1, the computer converts it to binary. Its highest bit is 1, so the value is treated as negative.
  6. The 8-bit binary representation of 197 is 11000101. Since its highest bit is 1, c1 is interpreted as negative.
  7. 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 11000101 gives 00111010; adding 1 gives 00111011.
  8. 00111011 is 59 in decimal, but because the highest bit is 1, c1 is interpreted as -59.
  9. Similarly, assigning 198 to c2 overflows and it is interpreted as -58.

Therefore, after overflow, c1 and c2 are -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.