1

I am learning C and I read in the Kernighan&Ritchie's book that integers int were included in a set specific set [-32767;32767]. I tried to verify this assertion by writing the following program which increment a variable count from 1 to the limit before it fall in negative numbers.

#include <stdio.h>

int main(void){
    int count = 1;
    while(count > 0){
        count++;
        printf("%d\n", count);
    }

    return 0;
}

And surprisingly I got this output:

1
......
2147483640
2147483641
2147483642
2147483643
2147483644
2147483645
2147483646
2147483647 -> This is a lot more than 32767?!
-2147483648 

I do not understand, Why do I get this output? And I doubt M. Ritchie made a mistake ;)

torr
  • 1,256
  • 3
  • 11
  • 20
  • You're thinking of 16-bit integers. Your compiler is clearly using a 32-bit implementation. –  Aug 23 '13 at 01:47
  • possible duplicate of [Size of C "int" is 2 bytes or 4 bytes?](http://stackoverflow.com/questions/11438794/size-of-c-int-is-2-bytes-or-4-bytes) – Michael Petrotta Aug 23 '13 at 01:48
  • K&R are explaining what an integer is *required* to do. It is allowed to do many things it is not required to do. – David Schwartz Aug 23 '13 at 02:00

2 Answers2

2

You're on a 32- or a 64-bit machine and the C compiler you are using has 32-bit integers. In 2's complement binary, the highest positive integer would be 31 bites, or 2^31-1 or 2147483647, as you are observing.

Note that this doesn't violate K&R's claim that the integer value includes the range [-32768;32767].

lurker
  • 56,987
  • 9
  • 69
  • 103
1

Shorts typically go from -32768 to 32767. 2^15th - 1 is the largest short.

Ints typically go from -2147483648 to 2147483647. 2^31st -1 is the largest int.

Basically ints are twice the size you thought.

dcaswell
  • 3,137
  • 2
  • 26
  • 25