varible declaration in macro

D

dis_is_eagle

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
 
R

Richard Heathfield

(e-mail address removed) 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.
 
G

Guest

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

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
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top