Too Big

Difficulty: ★ ★ ☆ ☆

The C language comes with a variety of data types that hold integer (whole number) values. But each type is limited by its size. The issue is to ensure that whatever value the program is manipulating never exceeds the given size.

Here is a summary of C language integer data types:

Type Width Minimum Range Maximum Range
signed char 1 byte -128 127
unsigned char 1 byte 0 255
short int 2 bytes -32,768 32,767
unsigned short int 2 bytes 0 65,535
int 4 bytes -2,147,483,648 2,147,483,647
unsigned int 4 bytes 0 4,294,967,295
long int 4 or 8 bytes (See above/below) (See above/below)
unsigned long int 4 or 8 bytes 0 (See above/below)
long long int 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
unsigned long long int 8 bytes 0 18,446,744,073,709,551,615

Various C functions, typedefs, and defined constants are used to help your code with these ranges and values, but in all cases there is a minimum and maximum number that sits safely in an integer space.

When I first learned to program, I was curious why programmers didn’t always use the maximum size, such as a long long. (Though, back then the largest integer value was a 16-bit int.) The answer is efficiency, but also storage conservation. Especially in the olden days, uses the smallest container that accommodated a given value was the best way to use memory.

The issue that triggers when to use the next largest integer container is overflow.

For example, the next char value after 127 is -128, which makes no sense to anyone unfamiliar with programming: Adding one to a char variable that holds 127 suddenly subtracts 255 from the value. Weird to mortals, but sensical to a programmer.

Ditto for unsigned data, where you add one to short int 65,535 and you’re back at zero again.

Finding the integer overflow values is the topic for this month’s C programming exercise.

Write a program that counts from zero on up. Flag when the value overflows for the char data type. Don’t cheat by using defined constants from the limits.h header file or anything else that’s already coded. Your program must report when the value flips for a signed and unsigned char value.

Here is a sample run from my solution:

'signed char' overflow at 127
'unsigned char' overflow at 255

Please try this exercise on your own before checking out my solution, which I’ll post in a week.

Leave a Reply