macro concatenation question

This is a discussion on macro concatenation question within the C Programming forums, part of the General Programming Boards category; Hi. I have the following code in my application: Code: #define PORT 1234 #define HOST "http://example.com:1234" Because the 1234 value ...

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    66

    macro concatenation question

    Hi.

    I have the following code in my application:

    Code:
    #define PORT 1234
    #define HOST "http://example.com:1234"
    Because the 1234 value appears in both definitions, I tried to concatenate the PORT to the HOST, so it would look like this:

    Code:
    #define PORT 1234
    #define HOST "http://example.com:" PORT
    When I try to compile the code everywhere where I used the HOST macro in some way the compiler gives me the following error:

    "error: expected ) before numeric constant"

    I guess this is because the PORT macro is an integer, the second is string, and when the compiler concatenates the two of them, converts the second macro to integer too.

    Can somebody tell me, how can I get rid of this problem?

    P.s.: If I define the PORT as string (#define PORT "1234") it is ok, but I would like to keep it integer.

    Thank you.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,439
    Like so
    Code:
    #include <stdio.h>
    
    #define PORT 1234
    #define MKSTR(x)    #x
    #define MKSTR2(x)   MKSTR(x)
    #define HOST "http://example.com:" MKSTR2(PORT)
    
    int main()
    {
      printf("%s\n",HOST);
      return 0;
    }
    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.

  3. #3
    Registered User
    Join Date
    May 2011
    Posts
    66
    Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MACRO question
    By baverlyhills2 in forum C Programming
    Replies: 10
    Last Post: 02-15-2012, 01:31 AM
  2. Macro question
    By Mole42 in forum C++ Programming
    Replies: 4
    Last Post: 01-14-2011, 03:41 PM
  3. int and char concatenation question
    By slowcoder in forum C Programming
    Replies: 3
    Last Post: 10-02-2006, 02:14 PM
  4. Macro question
    By caduardo21 in forum C Programming
    Replies: 1
    Last Post: 06-26-2005, 01:13 PM
  5. _T Macro Question
    By mrafcho001 in forum Windows Programming
    Replies: 9
    Last Post: 06-11-2005, 09:00 AM

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