typedef v/s macro
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 and #define x int"
There is no explanation of macro definition given in above sentence.
I want to know that whether #define x int is valid? If yes, then
how it is used?
Re: typedef v/s macro
Tagore <firstname.lastname@example.org> writes:
> 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 and #define x int"
> There is no explanation of macro definition given in above sentence.
> I want to know that whether #define x int 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;" (note that you need the semicolon) declares the
name "x" an an alias for the type "int", i.e., array of 10 ints.
"#define x int" (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
You can even declare pointers to type x, arrays of type x, and so
x arr; /* 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
will expand to
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.
Keith Thompson (The_Other_Keith) email@example.com <http://www.ghoti.net/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
|All times are GMT. The time now is 07:04 AM.|
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.