Know Your Limits

Back when I was a young, budding nerd, I popped off how there are always 8 bits in a byte. A much wiser programmer raised an eyebrow and quizzed me, “Always?”

Today it seems like all computers set a byte’s size equal to 8 bits, but back in the 1970s some computers held 7 bits in a byte, some 8, and some 9 or 10. A “byte” was merely a quantity and the number of bits dwelling within the byte wasn’t set by some international standard. It was set by the system’s hardware design.

To deal with such inconsistencies, the C language library offers you some assistance. To confirm various sizes and other hardware-specific trivia, you use the limits.h header file. It beats guessing.

The constants defined in the limits.h file are consistent. Their values, however, are unique to each system. On modern computers, a majority of the defined constants have the same values, although it’s good to run a test program just to be sure.

#include <stdio.h>
#include <limits.h>

int main()
{
    printf("%-16s\t%20s\n","VARIABLE","VALUE");
    printf("%16s\t%20d\n","bits in a byte",CHAR_BIT);
    printf("%16s\t%20d\n","char max",CHAR_MAX);
    printf("%16s\t%20d\n","char min",CHAR_MIN);
    printf("%16s\t%20d\n","signed char max",SCHAR_MAX);
    printf("%16s\t%20d\n","signed char min",SCHAR_MIN);
    printf("%16s\t%20d\n","unsigned char",UCHAR_MAX);
    printf("%16s\t%20d\n","short int max",SHRT_MAX);
    printf("%16s\t%20d\n","short int min",SHRT_MIN);
    printf("%16s\t%20d\n","int max",INT_MAX);
    printf("%16s\t%20d\n","int min",INT_MIN);
    printf("%16s\t%20ld\n","long max",LONG_MAX);
    printf("%16s\t%20ld\n","long min",LONG_MIN);

    return(0);
}

This code examines only a few of the constants defined in the limits.h header. These are primarily the integer constants, with the “bits per byte” value included for good measure.

If you’re curious about the printf() function formatting, refer to my post from October of 2013 on the %s text-formatting conversion character.

Here is the sample output on my system, which is a Macintosh running an older version of OS X:

VARIABLE        	               VALUE
  bits in a byte	                   8
        char max	                 127
        char min	                -128
 signed char max	                 127
 signed char min	                -128
   unsigned char	                 255
   short int max	               32767
   short int min	              -32768
         int max	          2147483647
         int min	         -2147483648
        long max	 9223372036854775807
        long min	-9223372036854775808

Other constants are defined in limits.h as well, a few of which are vital to know if you don’t want your code to crash. I’ll demonstrate one of them in next week’s Lesson. I’ll also show you how to handle the instance where a constant is undefined.