I came across a question where #define
was used to replace int
in the program as follows
#define type int
int main()
{
type *a,b;
}
Is this valid? Although it gave me error while I tried to print size of variable b saying b is undeclared. I want to know the specific reason behind this. Please let me know.
Some users told me that I have hidden some part of my code. I had not given the printf
statement in my above code snippet. Below is the code with printf
and the one which gives error
#define type int;
int main()
{
type* a, b;
printf("%d",sizeof(b));
}
Yes, it can be used, but keep in mind, there is significant difference between macro and type defintion. The preprocessor replaces "mechanically" each occurence of token, while typedef
defines true type synonym, thus the latter is considered as recommended way.
Here is an simple example to illustrate what it 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 from integer without a cast
return 0;
}
You may expect that type of p2
is int*
, but it is not. The preprocessed line is:
int* p1 = 0, p2 = 0;
On the other hand, typedef
defines both p3
and p4
as pointers to int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With