How to define C macro

Discussion in 'C Programming' started by Vittal, Jul 3, 2003.

  1. Vittal

    Vittal Guest

    Hello All,

    Here is a small C program,

    int a= 100;
    float b =99.99;

    Now I want to write a macro for TEST such that it outputs something like this

    int a=100;
    float b =99.99;
    printf(" The value of a = %d \n",a);
    printf(" The value of b = %f \n",b);

    I tried to write macro like this, but its not working

    #define TEST(a,b) printf(" The value of a = b \n",a)

    Can somebody help me in this?

    Vittal, Jul 3, 2003
    1. Advertisements

  2. Try

    #define TEST(a,b) printf(" The value of " #a " = " #b " \n", a)

    (The syntax #foo is a special preprocessing thingamabob that says
    "take the value of foo and stick it in a string literal." Putting
    two string literals next to each other - "foo" "bar" - concatenates
    them - producing the equivalent of "foobar". [This *only* works with
    compile-time literals!] So the above stringizes 'a' and 'b' and
    sticks them in the string.)

    Untested code, may not work if a or b are macros themselves. I.e.,

    TEST(INT_MAX, %d);

    may do incorrect things. Someone else will post that FAQ. :)

    Arthur J. O'Dwyer, Jul 3, 2003
    1. Advertisements

  3. Vittal

    Marc Boyer Guest

    #define TEST(a,b) printf("The value of " #a " = " #b "\n", a)

    Interresting question in fact.

    Marc Boyer
    Marc Boyer, Jul 3, 2003
  4. Hi Vittal,

    You can use the define:
    #define TEST(fmt,val) ((void)printf("The value of %s = "fmt"\n",#val,val))
    The format(fmt) is just a string and is concatenated with the rest of the
    #val is also a string (so "a" or "b" in your example)
    val is the value.


    #include <stdio.h>

    #define TEST(fmt,val) ((void)printf("The value of %s = "fmt"\n",#val,val))

    int main()
    int a=100;
    float b=99.99F;

    return 0;
    Marco de Boer, Jul 3, 2003
  5. Vittal

    Dan Pop Guest

    Obviously, since the preprocessor doesn't touch the contents of string
    Use the # operator and take advantage of the adjacent string splicing
    feature of C:

    #define TEST(a,b) printf(" The value of " #a " = " #b " \n", a)

    Not very easy to read, but it gets the job done.

    Dan Pop, Jul 3, 2003
    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.