Monday, October 17, 2011

Importance of 'typedef'ing

Some people ask me why do we need to typedef some datatypes. This is basically to maintain portability across compilers.

We put all typedefs in a single header file. When porting across compilers if any datatype related problem arrives, it is required to change only the header file. So we have single place changes rather than refactoring the entire code which would have been cumbersome.

For ex:

Assume a legacy code like this. In "C" we did not have bool until C99. The older code may look like this

typedef enum __BOOL__ { FALSE, TRUE }BOOL;

and wherever we need to use it we apply as "BOOL var = TRUE" etc..

gcc allows _Bool by default nowadays. So above code can be easily ported to _Bool. Here it goes.

typedef _Bool BOOL;
#define FALSE 0
#define TRUE 1

Bingo!! In a single place we did the modification and entire modification has same effect as earlier. The modification applies to all places without any changes to existing BOOL types.

Note that without 'typedef'ing enum __BOOL__ to BOOL, it would have been difficult to make changes at one shot (because of enum __BOOL__ declaration).

There may be lot other advantages. If someone reading the blog, comment on the same if you have more suggestions.

No comments:

Post a Comment