By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,750 Members | 1,165 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,750 IT Pros & Developers. It's quick & easy.

varible declaration in macro

P: n/a
Hi.If I define a macro which contains a variable declaration,then
during expansion the declaration will not be placed at the beginning of
the program,but somwhere within it.How can I overcome it?

Eric

Nov 7 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
di**********@yahoo.com said:
Hi.If I define a macro which contains a variable declaration,then
during expansion the declaration will not be placed at the beginning of
the program,but somwhere within it.How can I overcome it?
By not declaring the variable within the macro.

But if you must do so, then you can use {} to create a local scope for the
variable:

#define swap(arithmetictype, x, y) \
{ arithmetictype temp = x; x = y; y = temp; }

Usage:
int i = 42;
int j = 6;
swap(int, i, j)

The variable ceases to exist at the point that the } is reached. Although it
is not, strictly speaking, necessary, some people like to wrap a dummy
do-while around the compound statement, so that they can see a nice normal
semicolon at the end of the macro. Other people, such as myself, prefer not
to play such games with macros at all, and would rather write a function to
do whatever-it-is instead.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Nov 7 '06 #2

P: n/a
dis_is_ea...@yahoo.com wrote:
Hi.If I define a macro which contains a variable declaration,then
during expansion the declaration will not be placed at the beginning of
the program,but somwhere within it.How can I overcome it?
C's macros are purely text substitution and cannot ever insert text
other than where they are used. You can either use a mode of your
compiler which accepts variable declarations in the middle of a program
(in the current version of the C standard, this is allowed), or you can
rewrite the macro (for example, if it is to be used as a statement, by
surrounding it with { and }).

Nov 7 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.