Quoting symbol in CPP

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul J. Lucas

    Quoting symbol in CPP

    Given this:

    #define NUM 100

    I was to use a CPP macro like:

    char *p = MACRO(NUM);

    and have MACRO defined such that it would expand to:

    char *p = "100";

    I tried:

    #define MACRO(X) #X

    but, for MACRO(NUM), that expands to:

    char *p = "NUM";

    How can I get CPP to expand NUM first?

    - Paul
  • Szabolcs Borsanyi

    #2
    Re: Quoting symbol in CPP

    On May 9, 10:26 pm, "Paul J. Lucas" <paul-nos...@nospam.l ucasmail.org>
    wrote:
    Given this:
    >
            #define NUM 100
    >
    I was to use a CPP macro like:
    >
            char *p = MACRO(NUM);
    >
    and have MACRO defined such that it would expand to:
    >
            char *p = "100";
    >
    I tried:
    >
            #define MACRO(X) #X
    >
    but, for MACRO(NUM), that expands to:
    >
            char *p = "NUM";
    >
    How can I get CPP to expand NUM first?
    >
    - Paul
    The preprocessor will expand the macro parameters first, unless
    they appear next to a # (or ##).
    So try this:

    #define NUM 100
    #define MACRO(X) #X
    #define GOODMACRO(X) MACRO(X)

    char *p=GOODMACRO(NU M);

    GOODMACRO's argument is not following an #, so it is expanded, prior
    to
    looking at MACRO's meaning.

    Szabolcs

    Comment

    • vippstar@gmail.com

      #3
      Re: Quoting symbol in CPP

      On May 10, 12:26 am, "Paul J. Lucas" <paul-
      nos...@nospam.l ucasmail.orgwro te:
      Given this:
      >
      #define NUM 100
      >
      I was to use a CPP macro like:
      >
      char *p = MACRO(NUM);
      >
      and have MACRO defined such that it would expand to:
      >
      char *p = "100";
      >
      I tried:
      >
      #define MACRO(X) #X
      >
      but, for MACRO(NUM), that expands to:
      >
      char *p = "NUM";
      >
      Question 11.17 of the C-faq.
      <http://c-faq.com/>

      Comment

      Working...