Passing a semicolon or comma as a Macro argument

M

MattyWix

Hi,

How can I pass a semicolon or a comma as a macro argument.
I wish to build an expression that in some cases has a comma - eg
building a list of members for a structure, but in other instances has
a comma - eg building a list of arguments for a function.

MattyWix
 
C

Chris Dollin

MattyWix said:
How can I pass a semicolon or a comma as a macro argument.

I don't think you can. (I don't think you can switch off the
argument-separating function of the comma.) There might be
deferred-macro-expansion tricks you can pull. Someone else
can propose those: I get twitchy with clever macro tricks.
I wish to build an expression that in some cases has a comma - eg
building a list of members for a structure, but in other instances has
a comma - eg building a list of arguments for a function.

Well, I have three\\\\\four suggestions (likely there are more
possibilities):

(a) Have two macros. Share common text as other macros.

(b) Use a non-C macro preprocessor.

(c) Generate the code, don't macro-process it.

(d) Back off and review the problem and see if there's a
completely different way of solving it.

Looking at the code you've shown us, I'd go for (d).
 
C

Christopher Benson-Manica

Can you make any compilable example?

Sure:

#define comma ,
#define invoke(f,args) f(args)

#include <stdio.h>

int main(void)
{
invoke( printf, "Hello, world! %d, %d, %d\n" comma 1 comma 2 comma 3 );
return 0;
}

It should be obvious, however, that this is obfuscatory and thus a Bad
Idea. OP would be advised to find a different solution.
 
T

Thad Smith

(a) Have two macros. Share common text as other macros.

I like that approach:

#define LIST ITEM(a),ITEM(b),ITEM(c)

#define ITEM(x) x,
enum e {
LIST,
NUM_ENTRIES
};

#undef ITEM
#define ITEM(x) x;
struct s {
LIST
};
 
C

Chris Dollin

Thad said:
I like that approach:

#define LIST ITEM(a),ITEM(b),ITEM(c)

#define ITEM(x) x,
enum e {
LIST,
NUM_ENTRIES
};

#undef ITEM
#define ITEM(x) x;
struct s {
LIST
};

I don't like that implementation of it.
 
T

Thad Smith

Chris said:
I don't like that implementation of it.

It's a little messy, but the best I can think of to have multiple uses
of a single list using only C. You could do something nicer with an
external preprocessor. Feel free to contribute your own solution.
 

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

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top