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

This is a discussion on Can a macro evaluate ("return") a string? within the C Programming forums, part of the General Programming Boards category; Is it possible to "return" a string from a function-like macro? I know macros don't really "return" things, but is ...

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    12

    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:

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

    Code:
    strcpy(somefield,SN2ALG(44));
    In other words, any place you'd have a string.

    The actual code is something like

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

    Code:
    #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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 10: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, 02:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21