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

Discussion in 'C Programming' started by Ann O'Nymous, May 14, 2010.

  1. Ann O'Nymous

    Ann O'Nymous Guest

    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};
     
    Ann O'Nymous, May 14, 2010
    #1
    1. Advertisements

  2. Ann O'Nymous

    Ian Collins Guest

    Try

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

    Look up the preprocessor # and ## operators.
    Now that's just asking too much!
     
    Ian Collins, May 14, 2010
    #2
    1. Advertisements

  3. Ann O'Nymous

    Ann O'Nymous Guest

    Cool! Thanks!
    That's what I figured... :)
     
    Ann O'Nymous, May 14, 2010
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.