Thread: Can a macro evaluate ("return") a string?

  1. #1
    Registered User
    Join Date
    Apr 2010

    Can a macro evaluate ("return") a string?

    Is it possible to "return" a string from a function-like macro? I know macros don't really "return" things, but is it possible to have the macro evaluate to a string?

    For example, I have some code that takes a chess board square number (0...63) and converts it to "A1", "D1", etc. I was thinking of rewriting it as a macro, but I want to do things like this:

    printf ("Square is %s\n",SN2ALG(44));

    In other words, any place you'd have a string.

    The actual code is something like

    #define SN2ALG(x) concatenation of ((x >> 3)+'A') and (x & 7), yielding A3, D5, or whatever
    Something like:

    #define SN2ALG(x) sprintf("%c%c",((x >> 3)+'A'), (x & 7))
    ...but of course, that doesn't work but sprintf requires a string name - it's not a drop-in escape mechanism.

    I can certainly put it in a function, of course...just comparing options...though I don't think there is one in this case ;-)

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Perhaps the stringify and concatenation operators (# and ##)
    Stringification - The C Preprocessor
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM