Shanbhag Vinit
Shanbhag Vinit

Reputation: 139

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));
}

Upvotes: 4

Views: 2605

Answers (3)

phuclv
phuclv

Reputation: 42002

For simple types like your example it'll work, although it won't work as expected when declaring multiple variables one the same statement as Grzegorz Szpetkowski said. For more complex cases it might not work at all, as the texts in macros are only blindly replaced.

For example to declare a function pointer with typedef:

typedef int(*int_func)(int);
func some_function_pointer;

You can't use a simple macro like above as the syntax for function pointers is different, and you'll also need different macros for declaring a variable or casting one.

#define int_func_declaration(f) int(*f)(int)
#define int_func_cast(f) ((int(*)(int))f)

int_func_declaration(some_function_pointer) = int_func_cast(some_pointer_value);

Upvotes: 1

Karthik Kakarla
Karthik Kakarla

Reputation: 11

The mistakes in your program are:

  1. There should not be any semi column in the #define preprocessor command.
  2. There is no meaning for the * after type in the line type* a,b;. If you like of declaring a pointer then you should declare like this type *a, b;
  3. You forgot to include stdio.h header file in the beginning of the code

Click here for the corrected code.

Upvotes: 0

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37954

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.

Upvotes: 7

Related Questions