c preprocessor - Can #define be used to replace type declaration in c? -
i came across question #define used replace 'int' in program follows
#define type int int main() { type *a,b; }
is valid?although gave me error while tried print size of variable b saying b undeclared. want know specific reason behind this. please let me know.
some users told me have hidden part of code. had not given printf statement in above code snippet. below code printf nd 1 gives error
#define type int; int main() { type* a, b; printf("%d",sizeof(b)); }
yes, can used, keep in mind, there significant difference between macro , type defintion. preprocessor replaces "mechanically" each occurence of token, while typedef
defines true type synonym, latter considered recommended way.
here simple example illustrate means in practice:
#define type_int_ptr int* typedef int *int_ptr; int main(void) { type_int_ptr p1 = 0, p2 = 0; int_ptr p3, p4; p3 = p1; p4 = p2; // error: assignment makes pointer integer without cast return 0; }
you may expect type of p2
int*
, not. preprocessed line is:
int* p1 = 0, p2 = 0;
on other hand, typedef
defines both p3
, p4
pointers int
.
Comments
Post a Comment