Monday, April 13, 2015

C language from BaseBand Processor Eng perspective Part-2 DEFINE vs TYPEDEF

Okay ...one important thing in modem code which you will find in most of the places will be

#define   and typedef .

#define is preprocessor. It is used to replace a text/word with a some formula or constant value.
It is helpful when we need to replace a given formula or constant in lot of place in the code. Also we can use this in place of loops. It make code easier to read.

typedef if used to define a new datatype.

Now the below code will behave same.
-----------------------------------------------------------------------------------

#define WORD int
typedef int dword;

void main(){ WORD a =10; dword b=10; cout << a ; cout << b; }

// Both will print 10
--------------------------------------------------------------------------------------

But you can clearly see difference for below code

--------------------------------------------------------------------------------------

#define WORD int *
typedef int * dword;

void main(){ WORD t,u ; dword a,b; }

// Here a,t,b  will be pointers   and  u will be int .
// U  will not be pointer , Since WORD will simply be replaced by  int * a,b .

The difference is much more visible when we define functions pointers.

typedef void(*func_point)(void);
// Now we can use func_point to define new functions whose output and input are nothing.

func_point function;

// Here function is function pointer and can be assigned function whose input/output is no parameters.

but we can't do same using #define

#define FUNC_POINT void(*func_point)(void).



So remember even though sometimes both can do other work, better to

reserve #define  for loops, constants and formulas.

and typedef  to define new type which can be data type or functions pointer type.

No comments:

Post a Comment