Hi all,
I'm running through the book "The C Programming Language" by Kernighan & Ritchie and I'm having some trouble with one of the exercises.
"Write a program to determine the ranges of char, int, short and long variables, both signed and unsigned, by printing appropriate values from standard headers and by direct computation."
using standard headers:
#include <stdio.h>
#include <limits.h>
main() {
printf("The range of int signed is %d to %d\n", INT_MIN, INT_MAX);
printf("The range of char signed is %d to %d\n", CHAR_MIN, CHAR_MAX);
printf("The range of short signed is %d to %d\n", SHRT_MIN, SHRT_MAX);
printf("The range of long signed is %ld to %ld\n\n", LONG_MIN, LONG_MAX);
printf("The range of int unsigned is 0 to %u\n", UINT_MAX);
printf("The range of char unsigned is 0 to %u\n", UCHAR_MAX);
printf("The range of short unsigned is 0 to %u\n", USHRT_MAX);
printf("The range of long unsigned is 0 to %lu\n", ULONG_MAX);
}
the output being:
The range of int signed is -2147483648 to 2147483647
The range of char signed is -128 to 127
The range of short signed is -32768 to 32767
The range of long signed is -2147483648 to 2147483647
The range of int unsigned is 0 to 4294967295
The range of char unsigned is 0 to 255
The range of short unsigned is 0 to 65535
The range of long unsigned is 0 to 4294967295
However, the values for INT_MIN and INT_MAX are shown in the appendices as being the same as SHRT_MIN and SHRT_MAX repsectively. Is this something that has just changed over the years?
My second problem regards using direct computation.
My code so far is as follows:
#include <stdio.h>
main() {
int i;
long l;
short s;
char c;
i = 0;
l = 0;
s = 0;
c = 0;
while (i != EOF)
i++;
while (l != EOF)
l++;
while (s != EOF)
s++;
while (c != EOF)
c++;
printf("The range of int unsigned is 0 to %u\n", i);
printf("The range of long unsigned is 0 to %lu\n", l);
printf("The range of short unsigned is 0 to %u\n", s);
printf("The range of char unsigned is 0 to %u\n", c);
}
for which the output is (after a good amount of time):
The range of int unsigned is 0 to 4294967295
The range of long unsigned is 0 to 4294967295
The range of short unsigned is 0 to 4294967295
The range of char unsigned is 0 to 4294967295
which is obviously not what I'm after. I was hoping that by increasing a "short" variable, for example, to EOF, it would stop within its range. Why is this not occuring?
- I do understand that my method is very innefficent and there is most likely a much better approach.
Any help would be much appreciated.