Question

I read that most programmers use typedef to ensure the portability.

when I write for example:

typedef int int16_t

typedef unsigned int uint16_t

As long as int16_t is the same as int (the only change is the name) so where is the portability here?! why shouldn't I use int directly ?!

another question: On different microcontrollers the size of int isn't constant, for example in AVR 32 size of int = 4 byte, while in AVR 8-bit, size of int = 2 bytes

What does it depend on and why does it change with the change of microcontroller?!

Was it helpful?

Solution

The size of type int is not exactly specified by C, it is only supposed to be at least equal to 16 bits. So, on some processor architecture, compiler implements it as 16 bits whereas on some other as 32 bits. So, if a programmer writes int a, it would take 2 byte on the 1st architecture and 4 byte on the second -- i.e. non-uniform behavior across platforms (lack of portability considering the 'size' aspect).

To avoid that, the types are defined using names like uint_16 or uint_32 in some global header files (say, types.h). Inside types.h, the user-defined types would be correctly mapped to the suitable native type -- and there may be processor specific defines in types.h. e.g. considering your example:-

#ifdef AVR_32
typedef unsigned int  uint_32
#else
typedef unsigned long uint_32  
#endif

Later, a programmer would use these types(uint_16, uint_32 etc.) and won't bother about the size himself.

OTHER TIPS

The name of the type int16_t implies that you want a 16-bit signed integer. This is not true for the type int; its implementation depends on the compiler, which in turn depends on the platform.

So you use typedef to gain the flexibility of using conditional definitions.

#ifdef PLATFORM_A
typedef int int16_t;
#else // any other platform
typedef short int16_t;
#endif

The number of bits in the standard integer type usually depends on the size of the CPU registers and the width of the data bus between the CPU and the memory. So, generally, you can assume that an int has the most effective size that your CPU can handle.

Typedefs in the context of portability are generally used in preprocessor macros with conditional compiling:

#if defined(INTEL_PROCESSOR)
typedef int my_desired_integer;
#elif defined(POWER_PC)
typedef long int my_desired_integer;
#elif defined(SOME_OTHER_WEIRD_PROCESSOR_OR_OS)
typedef short int my_desired_integer;
#endif

Then you use my_desired_integer everywhere in your code and the preprocessor will make sure to put the right type into the typedef.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top