Let's say we had a simple function for returning the amount of days in
a month:
unsigned DaysInMonth(uns igned const month)
{
switch (month)
{
case 8:
case 3:
case 5:
case 10: return 30;
case 1: return 28;
default: return 31;
}
}
Notice the integer type I've used, i.e. "unsigned int" rather than
"unsigned char" or "unsigned short".
Many of the microcontroller s (i.e. a small chip that has a CPU and
RAM, basically it's a tiny little computer) in use nowadays do
arithmetic on 8-Bit numbers.
An example of a prevalent microcontroller nowadays would be the
PIC16F684. It's only got about 35 different CPU instructions. All of
the arithmetic instructions work on 8-Bit registers.
In my little code snippet above, the biggest number used is 31, which
of course would fit inside an "unsigned char".
In C, the plain "int" type is described as the "natural" type for the
system. I think a lot of people agree that this is the type you use
when you "just want to store a number", and I think a lot of people
expect it to be the fastest integer type.
The only problem with int, however, is that it must be at least 16-
Bit.
On an 8-Bit microcontroller such as the PIC16F684, this of course
means that int will NOT be the most efficient type. The problem with
this however is that we have code snippets like the one above that
think they're using the best integer types for the job. If we were to
re-write the code for an embedded system, we'd probably have:
char unsigned DaysInMonth(cha r unsigned const month)
{
switch (month)
{
case 8:
case 3:
case 5:
case 10: return 30;
case 1: return 28;
default: return 31;
}
}
I'd like now to bring up the topic of portable programming. In my own
code, I've begun to use types such as:
uint_fast8_t
Basically I'm saying "I want the fastest integer type whose range is
at least up to 255".
In this way, I can write code that will peform optimally on both
embedded systems and PC's.
To people out there who are enthusiastic about writing portable code,
do you think it's time we started using types like uint_fast8_t
instead of "unsigned int"?
Of course, even if our target platform doesn't supply an stdint.h, we
can always have a default version of it, e.g.:
typedef char unsigned uint_fast8_t;
or:
typedef unsigned uint_fast8_t;
Comment