Quote:
|
Originally Posted by KSB
On some site I have seen the following answer of difference between typedef and #define:
e.g.
typedef char *string_t;
#define char *string_d
string_t s1,s2;
string_d s3,s4;
In the above declarations, s1,s2 and s3 are all declared as char * but s4 is declared as a char, which is probably not the intention.
Can any one please solve my following question:
1. Is it possible to declare #define as shown in above exmple ( #define basic_datatype new_name). Because as far as I know #define has only two forms,
i. #define FMAC(x,y) x here, then y
ii. #define NONFMAC some text here
2. If above #define is valid, then how it works?
|
When using the keywords #define, the compiler will physically go through and replace every instance with your define statement (excluding the #define keyword). It can also be used for macros, which sort of looks like what you defined in 'i':
#define Add(x,y) x+y
that's a macro. You can define variables like you did in some of your first examples, but you can also do the same thing with typedef. I would recommend typedef over #define when defining data. For instance, take the following declarations:
typedef float ARRAY[3];
ARRAY my_array;
If you wanted to do that with #define it would be messy and irratating:
#define ARRAY(name) float name[3]
ARRAY(my_array);
Typedefs also allow the same name to be used, which *can* be important, but mostly only for larger projects.