Can I do this in C? (another macro question)

A

Ann O'Nymous

I have a struct definition like this:

struct xxx {
int val;
char name[12];
int count;
};

and I want to create instances of this with a macro, where the name of
the struct instance is the first paramater appended with the string
"_A", the first field is the first parameter (defined elsewhere), the
second field is the character string (up to 11 chars + terminating null)
and the third field is the second parameter.

Something like this:

#define foo(name,f) struct xxx name_A = {name,"name",f};

but that's not quite correct. What I want to do is this:

foo(cat,1) expands to: struct xxx cat_A = {cat,"cat",1};
foo(dog,2) expands to: struct xxx dog_A = {dog,"dog",2};
foo(horse,9) expands to: struct xxx horse_A = {horse,"horse",9};

So, my questions are:
How can I append a string "_A" to a parameter to make a name for
the struct instance? Right now, it names every one literally "name_A".

How can I get C to substitute the first parameter between the quote
marks? Right now it substitutes the string "name" each time with
no substitution.

Actually, what I'd also really like is to also find a way to convert the
string passed to upper case before substitution. I'd really like
foo(sheep,6) to expand to: struct xxx sheep_A = {sheep,"SHEEP",6};
 
I

Ian Collins

I have a struct definition like this:

struct xxx {
int val;
char name[12];
int count;
};

and I want to create instances of this with a macro, where the name of
the struct instance is the first paramater appended with the string
"_A", the first field is the first parameter (defined elsewhere), the
second field is the character string (up to 11 chars + terminating null)
and the third field is the second parameter.

Something like this:

#define foo(name,f) struct xxx name_A = {name,"name",f};

but that's not quite correct. What I want to do is this:

foo(cat,1) expands to: struct xxx cat_A = {cat,"cat",1};
foo(dog,2) expands to: struct xxx dog_A = {dog,"dog",2};
foo(horse,9) expands to: struct xxx horse_A = {horse,"horse",9};

Try

#define foo( name,f ) struct xxx name##_A = { name, #name, f }

Look up the preprocessor # and ## operators.
Actually, what I'd also really like is to also find a way to convert the
string passed to upper case before substitution. I'd really like
foo(sheep,6) to expand to: struct xxx sheep_A = {sheep,"SHEEP",6};

Now that's just asking too much!
 

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,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top