Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can #define be used to replace type declaration in c?

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));
}
like image 356
Shanbhag Vinit Avatar asked Sep 04 '25 17:09

Shanbhag Vinit


1 Answers

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.

like image 80
Grzegorz Szpetkowski Avatar answered Sep 07 '25 16:09

Grzegorz Szpetkowski