typedef v/s macro

T

Tagore

In my C text book, there is a section where use of typedef is compared
against macro. In this section, it uses a sentence as :

"Difference Between typedef int x[10] and #define x int[10]"

There is no explanation of macro definition given in above sentence.
I want to know that whether #define x int[10] is valid? If yes, then
how it is used?
 
K

Keith Thompson

Tagore said:
In my C text book, there is a section where use of typedef is compared
against macro. In this section, it uses a sentence as :

"Difference Between typedef int x[10] and #define x int[10]"

There is no explanation of macro definition given in above sentence.
I want to know that whether #define x int[10] is valid?

It's valid in the sense that it's perfectly legal.
If yes, then
how it is used?

Generally, it shouldn't be.

"typedef int x[10];" (note that you need the semicolon) declares the
name "x" an an alias for the type "int[10]", i.e., array of 10 ints.

"#define x int[10]" (note the lack of a semicolon) works on a lower
level. It's processed during an early stage of compilation, when
types don't yet exist. It causes the identifier "x" to be replaced by
the sequence of 4 tokens:
int [ 10 ]
regardless of whether that sequence makes sense in context.

If you want to declare an object of type "x", the typedef lets you do
so:
x obj;
You can even declare pointers to type x, arrays of type x, and so
forth:
x arr[20]; /* an array of 20 "x"s */
x *ptr; /* ptr is a pointer to an x */

If x is instead defined by the above #define directive, then
x obj;
will expand to
int[10] obj;
which is a syntax error. Macro expansion works on token sequences; it
ignores any higher-level syntax.

The comp.lang.c FAQ is at <http://www.c-faq.com/>. See question 1.13,
and follow the links to other questions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top