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 really hard to tell by looks of type how many bytes this variable takes on memory and how it looks in different system. For instance in 8-bit AVR-GCC compiler int is 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 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. In order 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 special naming format [u]intN_t. If number is for unsigned number you add u in front of type name and if do not add anything is unsigned. N indicates number of bits the variable will take. So this is 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 so that same same variable were 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 are a list of defines of min and max values of each types. You can use them when ever you need instead of grabbing calculator and defining by yourself:

….

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

….

There are other derivative tyepdefs for specific reasons like

typedef uint16_t intptr_t

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

uintmax_t myvar;

which is 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

Your email address will not be published. Required fields are marked *