Understanding the nature of #define

If I write something like

#define INT_PTR int*
INT_PTR ptr4, ptr5, ptr6;

In this case only ptr4 is pointer to an integer, rest of the values (ptr5 and ptr6) are integers. How they are taking the integer value ? Either it should give some compilation error.

Why is it this way that compiler is treating ptr5 and ptr6 as integers.


This actually has nothing to do with the #define, which is simply a textual replacement.

After the preprocessor phase (when the substitution takes place), you end up with:

int* ptr4, ptr5, ptr6;

and, because the * binds to the variable rather than the type, you create one integer pointer and two integers.

This is why I prefer to write:

int *xyzzy;

rather than:

int* xyzzy;

since the former makes it clearer that the * belongs to the variable. If you want to define a new type in C, the command is, surprisingly enough, typedef :-)

typedef int * INTPTR;
INTPTR ptr4, ptr5, ptr6;

That defines a new type that will apply to all variables that follow it, rather than just substituting text, as per the macro. In other words, the type INTPTR (int *) applies to all three of ptr4, ptr5 and ptr6.

Because to declare pointer objects you would do:

int *ptr4, *ptr5, *ptr6;

In C, the token * does not belong to the type information, so you have to repeat it when you declare several objects. Note that this is a frequent mistake in C.

What you can do is to typedef instead:

typedef int * INTPTR;

Need Your Help

RSpec: difficulty testing the assignment of an array of objects in the index action for different users

ruby-on-rails-4 rspec controller

I am writing a spec to test my readinglist controller. The a readinglist has a user_id and a micropost_id. I am trying to create 2 different users and test that the index action will display an lis...