Use fixed integer types to enhance portability

If you have programmed anything with C, you should be familiar with common data types like char, unsigned char, int, unsigned int, long int, long long int, etc. It is tough to tell by the looks of type how many bytes this variable takes on memory and how it looks in a different system. For instance in 8-bit AVR-GCC compiler int is a 16-bit type, while in ARM-GCC int is 32-bit. So int size is dependent on platform, compiler and runtime libraries. And switching between systems may trick you if you are not careful enough.

standard_int_types

You can always check the size of the variable by using sizeof() function. What to do if you need your code to be portable between different systems. Some great libraries could work on any system including 8-bit, 16-bit, 32-bit or 64-bit. To avoid this annoying problem, the ISO C99 standard introduced portable data types that are defined in stdint.h header file. If you open this header file of your default compiler tool-set you will find how things are organized. First of all, it checks the length of int types and then defines portable types by using unique naming format [u]intN_t. If the number is for an unsigned number, you add ‘u’ in front of the type name and do not add anything is unsigned. N indicates the number of bits the variable will take. So this is a simple table of common portable integer types:

portable_int_types

If you would like your program or parts of it be portable use those type definitions in the way that same variable were the same size either on 8-bit micro or 32-bit micro. They are also called portable integer types. Be sure to check other things inside stdint.h header file. You will find many useful things that are carried out for you. There is a list of defines of min and max values of each type. You can use them whenever you need instead of grabbing a calculator and defining by yourself:

#define INT16_MIN -32768 
#define INT16_MAX 32767 
#define UINT16_MAX 65535

There are other derivative typedefs for specific reasons like

typedef uint16_t intptr_t

which allows declaring pointer variables or if you want to have the largest integer you can also define variable using

uintmax_t myvar;

which is the same as

uint64_t myvar;
Bookmark the permalink.

One Comment

  1. Data size is dependent of platform,If programmer is not careful enough it has capability of ruining years of hardship.Myself has gone through this.This piece of information may be life saver for many of beginners.

Leave a Reply